如何使用Android';s列表视图

如何使用Android';s列表视图,android,listview,android-listview,scroll,Android,Listview,Android Listview,Scroll,我有一个可平铺的图像,我想用作列表视图的背景。我已经设置了setCacheColorHint(android.R.color.transparent)以便使用setBackgroundDrawable()正确查看背景图像 我的问题是,当我滚动列表视图时,图像会保持在原来的位置并且不会滚动。我假设这是正常行为,但我希望图像与文本一起滚动 有没有办法不用滚动我自己的ListView或设置每个单元格视图的背景就可以做到这一点?我没有为此使用XML,因为我希望它是动态的。创建一个类并使用ListView

我有一个可平铺的图像,我想用作
列表视图的背景。我已经设置了
setCacheColorHint(android.R.color.transparent)
以便使用
setBackgroundDrawable()
正确查看背景图像

我的问题是,当我滚动
列表视图时,图像会保持在原来的位置并且不会滚动。我假设这是正常行为,但我希望图像与文本一起滚动


有没有办法不用滚动我自己的
ListView
或设置每个单元格视图的背景就可以做到这一点?我没有为此使用XML,因为我希望它是动态的。

创建一个类并使用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);
        }
}
公共类MyCustomListView扩展了ListView
{
私有位图背景;
公共MyCustomListView(上下文、属性集属性)
{
超级(上下文,attrs);
background=BitmapFactory.decodeResource(getResources(),R.drawable.yourImage);//yourImage表示要移动的listView背景
}
@凌驾
受保护的void dispatchDraw(画布)
{
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();
用于(int y=顶部;y<高度;y+=背景高度)
{
对于(int x=0;x
现在,在XML文件中,使用如下列表视图::
//根据需要设置其他属性

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

在匿名类中也能很好地工作!我还必须设置
setScrollingCacheEnabled(false)
,以便在滚动时正确渲染