【问题标题】:How to get a background image scrollable with Android's ListView如何使用 Android 的 ListView 获取可滚动的背景图像
【发布时间】:2013-01-04 11:01:49
【问题描述】:

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

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

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

【问题讨论】:

标签: android listview android-listview scroll


【解决方案1】:

创建一个类并用 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);
        }
}

现在在您的 XML 文件中,像这样获取一个列表视图 ::
//根据需要设置其他属性

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

【讨论】:

  • 在匿名类中也能很好地工作!我还必须设置 setScrollingCacheEnabled(false) 才能在滚动时正确渲染。
猜你喜欢
  • 1970-01-01
  • 2011-06-30
  • 2015-01-30
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多