RecyclerView 设置最大高度

https://blog.51cto.com/u_14496797/5364085

方法1:使用约束布局

implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/view_constraintLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
 
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rc_filter"
            android:layout_width="match_parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_height="0dp"
            app:layout_constraintHeight_default="wrap"
            app:layout_constraintHeight_max="350dp" />
 
</androidx.constraintlayout.widget.ConstraintLayout>

  关键代码就是

1
2
3
android:layout_height="0dp"
app:layout_constraintHeight_default="wrap"
app:layout_constraintHeight_max="350dp"

  

当然也可以使用 ConstraintSet 在代码中设置来实现以上代码相同的结果:

1
2
3
4
5
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(view_constraintLayout);
constraintSet.constrainMaxHeight(R.id.rc_filter,Utils.dpToPx(mContext,350));
TransitionManager.beginDelayedTransition(view_constraintLayout);
constraintSet.applyTo(view_constraintLayout);

  方法2:重写 onMessure()方法

https://blog.csdn.net/baidu_40389775/article/details/107566050

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class MaxRecyclerView : RecyclerView {
    private var mMaxHeight = 0
 
    constructor(context: Context) : super(context) {}
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs)
    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(context, attrs)
    }
 
    private fun init(context: Context, attrs: AttributeSet?) {
        val arr = context.obtainStyledAttributes(attrs, R.styleable.MaxRecyclerView)
        mMaxHeight = arr.getLayoutDimension(R.styleable.MaxRecyclerView_maxHeight, mMaxHeight)
        arr.recycle()
    }
 
    override fun onMeasure(widthSpec: Int, heightSpec: Int) {
        super.onMeasure(widthSpec, heightSpec)
        val height = measuredHeight
        if (height > mMaxHeight) {
            setMeasuredDimension(widthSpec, mMaxHeight)
        }
    }
}

  如果测量的高度 大于 最大高度,则使用最大高度,否则默认使用测量的高度

<declare-styleable name="MaxRecyclerView">
        <attr name="maxHeight" format="dimension" />
</declare-styleable>

 

posted @   野生野鸡码农  阅读(524)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2017-09-21 语音听写的dialog
点击右上角即可分享
微信分享提示