how to scroll listview background with item

前端 未结 2 813
情歌与酒
情歌与酒 2021-01-14 01:32

I set a image as Listview background, if I want to scroll it with the item, what can I do?

for example: 1 is the background, if I scroll Listview down, it will chan

2条回答
  •  佛祖请我去吃肉
    2021-01-14 01:51

    The code by AndroidLearner works well, except for one bug, see my comment on AndroidLearner's answer. I wrote a Kotlin version of his code that fixes the bug, and also works with any background that was defined in xml like so:

    
    

    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
      }
    
    }
    

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

提交回复
热议问题