2

I have a tileable image I would like to use as the background of a ListView. I have already set setCacheColorHint(android.R.color.transparent) in order to view the background image properly, using setBackgroundDrawable().

My problem is the when I scroll the ListView, the image stays in-place and doesn't scroll too. I'm assuming this is normal behaviour, but I would like the image to scroll with the text.

Is there any way to do that without resorting to rolling my own ListView or setting the background of every cell's view? I'm not using XML for this, as I would like this to be dynamic.

Warpspace
  • 3,215
  • 3
  • 21
  • 24
  • possible duplicate of [how to scroll listview background with item](http://stackoverflow.com/questions/13457547/how-to-scroll-listview-background-with-item) – Jokus Jul 12 '14 at 14:08

1 Answers1

2

Create one class and extends it with ListView ::

public class MyCustomListView extends ListView
{
        private Bitmap background;

        public MyCustomListView(Context context, AttributeSet attrs) 
        {
            super(context, attrs);
            background = BitmapFactory.decodeResource(getResources(), R.drawable.yourImage);//yourImage means your listView Background which you want to move
        }

        @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);
        }
}

Now in your XML File ,take one listiview like this ::
//Set other attributes as per your requirement

 <com.test.MyCustomListView
    android:id="@+id/listview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
 </com.test.MyCustomListView>
AndroidLearner
  • 4,500
  • 4
  • 31
  • 62
  • Worked well with an anonymous class too! I also had to set `setScrollingCacheEnabled(false)` in order to render properly while scrolling. – Warpspace Jan 04 '13 at 14:45