引入
产品提了个常规需求,从底部弹框显示性别选择框,以前直接用原生AlertDialog或者自定义Dialog,这次想来个不一样的,查看开发文档发现BottomSheetDialog也可以实现,并且自带手势滑动和动画,于是开搞,实现效果如下。
效果图镇楼.png
效果可以。由于产品需要适配横屏,顺手试了下横屏,然后傻眼了,效果如下。
效果图镇楼.png
横屏状态下自定义的view没有显示全,需要手动上滑才能完全显示。习惯性点了下BottomSheetDialog源码,发现走onStart时BottomSheetBehavior把状态设置成STATE_COLLAPSED了,源码如下。
@Override
protected void onStart() {
super.onStart();
if (behavior != null && behavior.getState() == BottomSheetBehavior.STATE_HIDDEN) {
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
}
于是试着写了个Base类继承BottomSheetDialog,复写onStart方法,把状态设置成STATE_EXPANDED,运行后正常,代码如下:
public class BaseBottomSheetDialog extends BottomSheetDialog {
public BaseBottomSheetDialog(@NonNull Context context) {
super(context);
}
@Override
protected void onStart() {
super.onStart();
// for landscape mode
BottomSheetBehavior behavior = getBehavior();
behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
}
此时又发现个问题,由于我的测试机是一加7T,有美人痣前置摄像头,导致StatusBar是黑色的,截图看不出来,用另一个手机拍摄如下:
效果图镇楼.png
这个应该和StatusBar高度有关,于是复写onCreate方法,代码如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// for transparent
int screenHeight = ScreenUtil.getScreenHeight(getContext());
int statusBarHeight = ScreenUtil.getStatusBarHeight(getContext());
int dialogHeight = screenHeight - statusBarHeight;
Window window = getWindow();
if(null != window) {
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, dialogHeight == 0 ? ViewGroup.LayoutParams.MATCH_PARENT : dialogHeight);
}
}
测试后状态栏颜色也正常了,以下是整个BaseBottomSheetDialog的修改代码:
/**
* A base bottom sheet dialog that fix some bugs himself.
*
* @author majh
*/
public class BaseBottomSheetDialog extends BottomSheetDialog {
public BaseBottomSheetDialog(@NonNull Context context) {
super(context);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// for transparent
int screenHeight = ScreenUtil.getScreenHeight(getContext());
int statusBarHeight = ScreenUtil.getStatusBarHeight(getContext());
int dialogHeight = screenHeight - statusBarHeight;
Window window = getWindow();
if(null != window) {
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, dialogHeight == 0 ? ViewGroup.LayoutParams.MATCH_PARENT : dialogHeight);
}
}
@Override
protected void onStart() {
super.onStart();
// for landscape mode
BottomSheetBehavior behavior = getBehavior();
behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
}
效果
最终横竖屏效果如下图:
竖屏.png
横屏.png
CSDN地址:https://blog.csdn.net/nerv2013/article/details/106453948
GitHub地址:https://github.com/afterschoolkido