The code from AndroidLearner works well, except for one error, see my comment on AndroidLearner answers. I wrote a version of Kotlin's code that fixes the error, and also works with any background that was defined in xml as follows:
<ListViewWithScrollingBackground android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/some_background"/>
Here is the code:
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 } }
To convert Drawable to Bitmap I used this post.
source share