死去的记忆突然攻击我

59 阅读1分钟

ScrollView 嵌套ListView为什么只显示ListView 的一项? 知其然而不知其所以然,说的就是我了,之前写的代码 SimpleGame/app/src/main/java/com/example/simple/utils/AllItemListView.java at main · FaceWallHan/SimpleGame (github.com),现在才知道原因

image.png image.png ScrollView重写了super.measureChildWithMargins() image.png ListView执行onMeasure时的MeasureSpec.UNSPECIFIED状态 image.png

解决方案

class MyListView @JvmOverloads constructor(  
    context: Context,  
    attrs: AttributeSet? = null,  
    defStyleAttr: Int = 0  
) : ListView(context, attrs, defStyleAttr) {  
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {  
        //右移2位  
        val size = Int.MAX_VALUE.shr(2)  
        val newHeight = MeasureSpec.makeMeasureSpec(size, MeasureSpec.AT_MOST)  
        super.onMeasure(widthMeasureSpec, newHeight)  
    }  
}

image.png

  • widthMeasureSpec: Int, heightMeasureSpec: Int 会包含两个信息,第一个信息是模式:2位 值:30位
  • 为了不进到if (returnedHeight >= maxHeight),所以传30位二进制最大值
  • Int.MAX_VALUE2^31-1为32位,右移两位正好为30个1,为最大值

image.png image.png