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.