RecyclerView设置最大高度、宽度

节选自:RecyclerView设置最大高度、宽度


当RecyclerView属性设置为wrap_content+maxHeight时,maxHeight没有效果。

<android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        ...
        android:layout_height="wrap_content"
        android:maxHeight="300dp"
        ...
/>

查看源码时发现,当RecyclerView的LayoutManager#isAutoMeasureEnabled()返回true时,RecyclerView高度取决于children view的布局高度,并非取决于RecyclerView自身的测量高度。

@Override
protected void onMeasure(int widthSpec, int heightSpec) {
    ...
    if (mLayout.mAutoMeasure) {
        ...
        // now we can get the width and height from the children.
        mLayout.setMeasuredDimensionFromChildren(widthSpec, heightSpec);
        if (mLayout.shouldMeasureTwice()) {
            ...
            // now we can get the width and height from the children.
            mLayout.setMeasuredDimensionFromChildren(widthSpec, heightSpec);
        }
    } else {
      ...
    }
}

解决办法

因此,我们只需要重写LayoutManager的

public void setMeasuredDimension(Rect childrenBounds, int wSpec, int hSpec)

方法即可为RecyclerView设置最大宽高。

override fun setMeasuredDimension(childrenBounds: Rect, wSpec: Int, hSpec: Int) {
    super.setMeasuredDimension(childrenBounds, wSpec, View.MeasureSpec.makeMeasureSpec(maxHeight, AT_MOST))
}

发表评论