最近重構項目,想把之前的一些控件替換成BottomSheetDialog。最后選用的是更加方便的BottomSheetDialogFragment。也遇到了很多坑,寫出來分享一下。
1.BottomSheetDialogFragment背景圓角設置
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/white" />
<corners
android:topLeftRadius="20dp"
android:topRightRadius="20dp" />
</shape>
按這個代碼給根布局設置完成后,卻沒有顯示對應的圓角。所以我想這是不是BottomSheetDialog的背景是白色的,所以擋住了。把白色換成其他顏色后果然看出來:解決方法:
BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
View view = View.inflate(getContext(), R.layout.layout_room_more_setting, null);
dialog.setContentView(view);
((View) view.getParent()).setBackgroundColor(getResources().getColor(android.R.color.transparent));
設置BottomSheetDialog的背景為透明色。
2.彈出BottomSheetDialog背景變暗
默認情況下直接彈出BottomSheetDialogFragment背景會變暗,需求是不能變暗。可以通過設置style解決問題。
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.TransBottomSheetDialogStyle);
}
<style name="TransBottomSheetDialogStyle" parent="Theme.Design.Light.BottomSheetDialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:background">@android:color/transparent</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
這樣彈出Dialog時背景就不會變暗。
3.彈出的BottomSheetDialog占滿屏幕
如果BottomSheetDialog中內容很多的話彈出的Dialog首先會到達一個peekHeight,然后如果滑動內容,整個Dialog就會向上滑動,直到鋪滿屏幕。很多時候我們是不希望整個Dialog向上滑動到整個屏幕的,比如在需要實時預覽設置效果的畫面:
如果再向上滑動就會一直占滿整個屏幕,無法實時看到預覽的畫面。這時我們就需要控制BottomSheetDialog的peekHeight和最大高度。
在BottomSheetBehavior中有一個
setPeekHeight()
方法可以控制首次彈出的高度,BottomSheetDialog沒有將這個方法開放給我們。查看setContentView()
源碼:
@Override
public void setContentView(@LayoutRes int layoutResId) {
super.setContentView(wrapInBottomSheet(layoutResId, null, null));
}
再打開wrapInBottomSheet(layoutResId, null, null)
:
private View wrapInBottomSheet(int layoutResId, View view, ViewGroup.LayoutParams params) {
final FrameLayout container = (FrameLayout) View.inflate(getContext(),
R.layout.design_bottom_sheet_dialog, null);
final CoordinatorLayout coordinator =
(CoordinatorLayout) container.findViewById(R.id.coordinator);
if (layoutResId != 0 && view == null) {
view = getLayoutInflater().inflate(layoutResId, coordinator, false);
}
FrameLayout bottomSheet = (FrameLayout) coordinator.findViewById(R.id.design_bottom_sheet);
mBehavior = BottomSheetBehavior.from(bottomSheet);
mBehavior.setBottomSheetCallback(mBottomSheetCallback);
mBehavior.setHideable(mCancelable);
if (params == null) {
bottomSheet.addView(view);
} else {
bottomSheet.addView(view, params);
}
// We treat the CoordinatorLayout as outside the dialog though it is technically inside
coordinator.findViewById(R.id.touch_outside).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCancelable && isShowing() && shouldWindowCloseOnTouchOutside()) {
cancel();
}
}
});
// Handle accessibility events
ViewCompat.setAccessibilityDelegate(bottomSheet, new AccessibilityDelegateCompat() {
@Override
public void onInitializeAccessibilityNodeInfo(View host,
AccessibilityNodeInfoCompat info) {
super.onInitializeAccessibilityNodeInfo(host, info);
if (mCancelable) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_DISMISS);
info.setDismissable(true);
} else {
info.setDismissable(false);
}
}
@Override
public boolean performAccessibilityAction(View host, int action, Bundle args) {
if (action == AccessibilityNodeInfoCompat.ACTION_DISMISS && mCancelable) {
cancel();
return true;
}
return super.performAccessibilityAction(host, action, args);
}
});
bottomSheet.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
// Consume the event and prevent it from falling through
return true;
}
});
return container;
}
在第十行可以看到BottomSheetBehavior,這個BottomSheetBehavior是從R.id.design_bottom_sheet這個View獲取的。那么我們同樣可以通過這個方法獲取BottomSheetBehavior,然后設置peekHeight。
View view = bottomSheetDialog.getWindow().findViewById(android.support.design.R.id.design_bottom_sheet);
BottomSheetBehavior.from(view).setPeekHeight(1600);
由于我們的代碼沒有在Support包下面,所以不能直接寫R.id.design_bottom_sheet
,而是要寫成android.support.design.R.id.design_bottom_sheet
。
這時我們已經完成了設置首次彈出高度。接下來我們需要設置Dialog的最大高度。
查看BottomSheetDialog的源碼可以再onCreate()
方法中發現如下代碼:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
if (window != null) {
if (Build.VERSION.SDK_INT >= 21) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
}
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
}
}
這里面window.setLayout()
方法就是設置整個Dialog占滿屏幕,這樣如果內容過長就會一直向上滑動,直到占滿屏幕。那么我們只需要改變這個屬性即可。
mWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, mMaxHeight);
現在我們發現Dialog的高度是我們想要的高度了,但是Dialog沒有像預期一樣固定在屏幕底部。這時需要簡單設置下dialog的gravity即可:
bottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
需要注意的是需要在onCreate() 中對寬高進行設置,或者 show() 之后進行設置,否則高度設置不生效。
綜合上述的過程,可以對這個可以自定peekHeight和maxHeight的BottomSheetDialog做一個簡單的封裝,方便使用:
package com.zouludaifeng.daifeng.widget;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
/**
* @author sun on 2018/5/25.
*/
public class CustomHeightBottomSheetDialog extends BottomSheetDialog {
private int mPeekHeight;
private int mMaxHeight;
private boolean mCreated;
private Window mWindow;
private BottomSheetBehavior mBottomSheetBehavior;
public CustomHeightBottomSheetDialog(@NonNull Context context,int peekHeight,int maxHeight) {
super(context);
init(peekHeight, maxHeight);
}
public CustomHeightBottomSheetDialog(@NonNull Context context, int theme,int peekHeight,int maxHeight) {
super(context, theme);
init(peekHeight, maxHeight);
}
public CustomHeightBottomSheetDialog(@NonNull Context context, boolean cancelable, OnCancelListener cancelListener,int peekHeight,int maxHeight) {
super(context, cancelable, cancelListener);
init(peekHeight, maxHeight);
}
private void init(int peekHeight, int maxHeight) {
mWindow = getWindow();
mPeekHeight = peekHeight;
mMaxHeight = maxHeight;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCreated = true;
setPeekHeight();
setMaxHeight();
setBottomSheetCallback();
}
public void setPeekHeight(int peekHeight) {
mPeekHeight = peekHeight;
if (mCreated) {
setPeekHeight();
}
}
public void setMaxHeight(int height) {
mMaxHeight = height;
if (mCreated) {
setMaxHeight();
}
}
public void setBatterSwipeDismiss(boolean enabled) {
if (enabled) {
}
}
private void setPeekHeight() {
if (mPeekHeight <= 0) {
return;
}
if (getBottomSheetBehavior() != null) {
mBottomSheetBehavior.setPeekHeight(mPeekHeight);
}
}
private void setMaxHeight() {
if (mMaxHeight <= 0) {
return;
}
mWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, mMaxHeight);
mWindow.setGravity(Gravity.BOTTOM);
}
private BottomSheetBehavior getBottomSheetBehavior() {
if (mBottomSheetBehavior != null) {
return mBottomSheetBehavior;
}
View view = mWindow.findViewById(android.support.design.R.id.design_bottom_sheet);
// setContentView() 沒有調用
if (view == null) {
return null;
}
mBottomSheetBehavior = BottomSheetBehavior.from(view);
return mBottomSheetBehavior;
}
private void setBottomSheetCallback() {
if (getBottomSheetBehavior() != null) {
mBottomSheetBehavior.setBottomSheetCallback(mBottomSheetCallback);
}
}
private final BottomSheetBehavior.BottomSheetCallback mBottomSheetCallback
= new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet,
@BottomSheetBehavior.State int newState) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
dismiss();
BottomSheetBehavior.from(bottomSheet).setState(
BottomSheetBehavior.STATE_COLLAPSED);
}
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
}
};
}
4.java.lang.IllegalStateException: Fragment does not have a view
在BottomSheetDialog中使用ViewPager會報這個錯誤。錯誤的原因沒有深究,提供一個簡單的解決方案就是不要再onCreateDialog()
中創建Dialog,轉到onCreateView
中創建View,就不會報這個異常。
但是這么干又會帶來第一個問題里面提到的,背景變成了白色。如果直接在onCreateView()
或者onViewCreated()
里面調用
((View) view.getParent()).setBackgroundColor(getResources().getColor(android.R.color.transparent));
會報空指針異常,這時需要在onActivityCreated()
中調用這個方法,就可以避免這個問題。汗,一趟走過來,問題還真是不少。