Search code examples
androidbackgroundandroid-listviewandroid-listfragment

how to scroll listview background with item


I set a image as Listview background, if I want to scroll it with the item, what can I do?

for example: 1 is the background, if I scroll Listview down, it will change from

        1          
-----1-----1--------
   1         1
-1-------------1----

to

--------1----------
      1    1
---1----------1----
 1              1

maybe I could extends listview and override dispatchDraw, but if I use listFragment, what can I do ? anybody help me?


Solution

  • In your Activity's XML file define the listview like this ::

    (Define the property in this xml file as per your requirement)

    <com.example.MyCustomListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
    

    Create one Class named MyCustomListView ::

        public class MyCustomListView extends ListView
        {
    
           private Bitmap background;
    
        public MyCustomListView(Context context, AttributeSet attrs) 
        {
            super(context, attrs);
            background = BitmapFactory.decodeResource(getResources(), R.drawable.yourImageName);
        }
    
        @Override
        protected void dispatchDraw(Canvas canvas) 
        {
            int count = getChildCount();
            int top = count > 0 ? getChildAt(0).getTop() : 0;
            int backgroundWidth = background.getWidth();
            int backgroundHeight = background.getHeight();
            int width = getWidth();
            int height = getHeight();
    
            for (int y = top; y < height; y += backgroundHeight)
            {
                for (int x = 0; x < width; x += backgroundWidth)
                {
                    canvas.drawBitmap(background, x, y, null);
                }
            }
            super.dispatchDraw(canvas);
        }
     }
    

    Hope this will solve your problem :)