dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
BottomSheetDialog d = (BottomSheetDialog) dialog;
FrameLayout bottomSheet = (FrameLayout) d.findViewById(android.support.design.R.id.design_bottom_sheet);
BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED);
}
});
我遇到NullPointException是BottomSheetBehavior.from(bottomSheet)
因为d.findViewById(android.support.design.R.id.design_bottom_sheet)
返回null。
真奇怪。我在DEBUG模式下将这行代码添加到Android Monitor中的Watches,发现它正常返回Framelayout。
这是wrapInBottomSheet
BottomSheetDialog中的代码:
private View wrapInBottomSheet(int layoutResId, View view, ViewGroup.LayoutParams params) {
final CoordinatorLayout coordinator = (CoordinatorLayout) View.inflate(getContext(),
R.layout.design_bottom_sheet_dialog, null);
if (layoutResId != 0 && view == null) {
view = getLayoutInflater().inflate(layoutResId, coordinator, false);
}
FrameLayout bottomSheet = (FrameLayout) coordinator.findViewById(R.id.design_bottom_sheet);
BottomSheetBehavior.from(bottomSheet).setBottomSheetCallback(mBottomSheetCallback);
if (params == null) {
bottomSheet.addView(view);
} else {
bottomSheet.addView(view, params);
}
if (shouldWindowCloseOnTouchOutside()) {
coordinator.findViewById(R.id.touch_outside).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isShowing()) {
cancel();
}
}
});
}
return coordinator;
}
有时,我发现R.id.design_bottom_sheet
不等于android.support.design.R.id.design_bottom_sheet
。它们在不同的R.java中具有不同的值。
因此,我更改android.support.design.R.id.design_bottom_sheet
为R.id.design_bottom_sheet
。
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
BottomSheetDialog d = (BottomSheetDialog) dialog;
FrameLayout bottomSheet = (FrameLayout) d.findViewById(R.id.design_bottom_sheet);
BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED);
}
});
现在不再有NullPointException。
BottomSheetDialogFragment
从折叠行为扩展到展开行为时,它使外观显得混乱(在打开的动画中似乎跳过帧)。编辑:在Android棉花糖和KitKat设备上测试了此内容