我设置的图像作为背景的Listview,如果我想与该项目滚动它,我该怎么办?
例如:1是背景,如果我滚动列表视图下来,它将从改变
1
-----1-----1--------
1 1
-1-------------1----
至
--------1----------
1 1
---1----------1----
1 1
也许我可以延伸ListView和覆盖dispatchDraw,但如果我用listFragment,我该怎么办? 有人帮我吗?
在你活动的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);
}
}
希望这将解决你的问题:)
通过AndroidLearner代码工作得很好,除了一个错误,看到我对AndroidLearner的答复意见。 我写了他的代码,修复了这个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
我用这个职位。