4

我将图像设置为 Listview 背景,如果我想用项目滚动它,我该怎么办?

例如:1 是背景,如果我向下滚动 Listview,它将从

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

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

也许我可以扩展 listview 并覆盖 dispatchDraw,但如果我使用 listFragment,我能做什么?有人帮我吗?

4

2 回答 2

6

在您的活动的 XML 文件中定义这样的列表视图::

(根据您的要求在此 xml 文件中定义属性)

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

创建一个名为 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);
    }
 }

希望这能解决你的问题:)

于 2012-11-20T12:46:33.150 回答
0

AndroidLearner 的代码运行良好,除了一个错误,请参阅我对 AndroidLearner 答案的评论。我编写了他的代码的 Kotlin 版本来修复错误,并且还适用于在 xml 中定义的任何背景,如下所示:

<ListViewWithScrollingBackground
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/some_background"/>

这是代码:

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.widget.ListView


class ListViewWithScrollingBackground(context: Context, attrs: AttributeSet)
: ListView(context, attrs) {

  private val background by lazy { getBackground().toBitmap() }

  override fun dispatchDraw(canvas: Canvas) {
    var y = if (childCount > 0) getChildAt(0).top.toFloat() - paddingTop else 0f
    while (y < height) {
      var x = 0f
      while (x < width) {
        canvas.drawBitmap(background, x, y, null)
        x += background.width
      }
      y += background.height
    }
    super.dispatchDraw(canvas)
  }

  private fun Drawable.toBitmap(): Bitmap = 
    if (this is BitmapDrawable && bitmap != null) bitmap else {
    val hasIntrinsicSize = intrinsicWidth <= 0 || intrinsicHeight <= 0
    val bitmap = Bitmap.createBitmap(if (hasIntrinsicSize) intrinsicWidth else 1,
      if (hasIntrinsicSize) intrinsicHeight else 1, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    setBounds(0, 0, canvas.width, canvas.height)
    draw(canvas)
    bitmap
  }

}

For the conversion of the Drawable to a Bitmap I used this post.

于 2018-01-11T12:08:10.680 回答