查了资料可以有三种实现方式:
第一种:直接在代码中判断,当recycler元素大于某个个数时,就将recycler的高度固定;
private fun setRecyclerMaxHeigh(view: RecyclerView, maxHeight: Float) {
val lp: ViewGroup.LayoutParams = view.getLayoutParams()
if (view.childCount> 4) {
Log.d("myLog", view.childCount.toString())
lp.height = DensityUtil.dip2px(maxHeight)
} else {
Log.d("myLog", view.childCount.toString())
lp.height = DensityUtil.dip2px(0f)
}
view.layoutParams = lp
}第二种:重写RecyclerView加一个最大高度的属性MaxHeightRecyclerView:
public class MaxHeightRecyclerView extends RecyclerView {
private int mMaxHeight;
public MaxHeightRecyclerView(Context context) {
super(context);
}
public MaxHeightRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context, attrs);
}
public MaxHeightRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize(context, attrs);
}
private void initialize(Context context, AttributeSet attrs) {
TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightRecyclerView);
mMaxHeight = arr.getLayoutDimension(R.styleable.MaxHeightRecyclerView_max_height, mMaxHeight);
arr.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mMaxHeight > 0) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxHeight, MeasureSpec.AT_MOST);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}第三种:如果你的父布局是constraintLayout,可以用此布局来约束RecyclerView标记进行以下更改:
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintHeight_default="wrap"
app:layout_constraintHeight_max="280dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/line/>关键属性是这三个:
android:layout_height="0dp"
app:layout_constraintHeight_default="wrap"
app:layout_constraintHeight_max="280dp"版权声明:本文为DDD318原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。