项目中遇到的需求:
页面中显示列表,这个列表最多显示三个item的高度。如果item小于三个,就自适应高度显示;如果item超过三个,高度固定为三个item的高度,超出的item需要滑动显示。
根据需求来看,直接固定RecyclerView高度肯定不行。那怎么搞,自定义RecyclerView?貌似很麻烦,而且不容易处理。
所以我换了一种思路,不直接对RecyclerView进行处理,而是给RecyclerView增加父布局,对其父布局进行处理,这就容易多了。
主要代码如下:
xml文件:
<RelativeLayout
android:id="@+id/rl_recy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/main_tv_title">
<android.support.v4.widget.NestedScrollView
android:id="@+id/nestedscroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_product"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp" />
</android.support.v4.widget.NestedScrollView>
</RelativeLayout>
.java代码:
//更新还款列表显示
public void updateData(List<BorrowProductBean> productList){
mProductList.clear();
if(productList!=null){
mProductList.addAll(productList);
//高度最多显示三个item的高度,如果多于3个条目,让其可滑动显示。如果少于三个条目,则自适应高度
if(mProductList!=null && mProductList.size()>3){
resize();
}
mProductTypeAdapter.updateAdapterData(mProductList);
}
}
private void resize(){
mDialogBinding.nestedscroll.setScrollbarFadingEnabled(false);
ViewGroup.LayoutParams linearParams = mDialogBinding.rlRecy.getLayoutParams();
linearParams.height = DensityUtil.dp2px(mContext,76 * 3);//超高3个就固定三个item的高度
mDialogBinding.rlRecy.setLayoutParams(linearParams);
}