我将图像设置为Listview背景,如果我想用项目滚动它,我该怎么办?
例如: 1是背景,如果我向下滚动Listview, 它会改变
1
-----1-----1--------
1 1
-1-------------1----
到
--------1----------
1 1
---1----------1----
1 1
也许我可以扩展listview并覆盖dispatchDraw, 但如果我使用listFragment,我该怎么办? 有人帮帮我吗?
答案 0 :(得分:6)
在Activity的XML文件中定义listview,如::
(根据您的要求在此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);
}
}
希望这能解决您的问题:)
答案 1 :(得分:0)
AndroidLearner的代码运行良好,除了一个错误,请参阅我对AndroidLearner的回答的评论。我写了一个Kotlin版本的代码修复了这个bug,也适用于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
}
}
要将Drawable
转换为Bitmap
我使用的this帖子。