BottomSheetDialogFragment+RecyclerView导致的高度问题
遇到的问题
BottomSheetDialogFragment 弹出一个 RecyclerView+Button做列表选择菜单的时候,由于设置了RecyclerView的高度为wrap_content导致Item过多的时候,Button被ReclerView遮挡。
原因
导致这个问题的原因是因为RecyclerView占满了整个BottomSheetDialogFragment 的根布局
解决
1.更改布局层次,比如根布局用相对布局,RecyclerView设置paddingBottom高度为button的高度
2.自定义RecyclerVeiw,增加maxheight属性
// 自定义RecyclerView部分
public class MaxHeightRecyclerView extends RecyclerView {
private int maxHeight = 0;
public MaxHeightRecyclerView(@NonNull Context context) {
this(context, null);
}
public MaxHeightRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public MaxHeightRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightRecyclerView);
maxHeight = array.getLayoutDimension(R.styleable.MaxHeightRecyclerView_maxHeight, maxHeight);
array.recycle();
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
if (maxHeight > 0) {
heightSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
}
super.onMeasure(widthSpec, heightSpec);
}
}
<declare-styleable name="MaxHeightRecyclerView">
<attr name="maxHeight" format="dimension"/>
</declare-styleable>
设置BottomSheetDialogFragment固定高度的方法
只需要重写onStart方法就可以了
override fun onStart() {
super.onStart()
dialog?.apply {
val bottomSheet = findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
bottomSheet?.apply {
layoutParams.height = dip(260) }
}
}
禁用下滑取消
直接设置
isCancelable = false