BottomSheetDialogFragment使用的注意點

最近重構項目,想把之前的一些控件替換成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的背景是白色的,所以擋住了。把白色換成其他顏色后果然看出來:
Screenshot_2018-05-24-11-20-50

解決方法:

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向上滑動到整個屏幕的,比如在需要實時預覽設置效果的畫面:

image.png

如果再向上滑動就會一直占滿整個屏幕,無法實時看到預覽的畫面。這時我們就需要控制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()中調用這個方法,就可以避免這個問題。汗,一趟走過來,問題還真是不少。

參考:http://www.voidcn.com/article/p-vtgwgqnn-nq.html

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,908評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,324評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,018評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,675評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,417評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,783評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,779評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,960評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,522評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,267評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,471評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,009評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,698評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,099評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,386評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,204評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,436評論 2 378

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,716評論 25 708
  • ¥開啟¥ 【iAPP實現進入界面執行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,491評論 0 17
  • 彼岸花開 靜靜在黃泉等待 妖艷的血紅 純白已不復存在 紅塵遺夢 誰是誰的罪孽 彼岸審判 千古遺淚 不知濕了誰的眼眸……
    西嶺雪貝貝閱讀 228評論 0 2