七、BottomDialog、BottomSheetDialog、BottomSheetDialogFragment的使用

一、簡單介紹

這三個不同普通的Dialog,它們都可以通過手勢拖動來進行隱藏或顯示;
各自的特點:

    1. bottomDialog
      依賴于CoordinatorLayout和BottomSheetBehavior,需要將底部菜單作為CoordinatorLayout的子View,并且需要設置app:layout_behavior="@string/bottom_sheet_behavior",適合固定的底部菜單,但是不夠靈活,需要依賴父布局和behavior;
  • 2.bottomSheetDialog
    使用方式類似dialog,布局可以使動態的布局,比如是個Recycler;
  • 3.bottomSheetDialogFragment
    通過繼承與BottomSheetFragment來實現底部菜單布局,適用于動態指定的布局,并且根據Fragment的生命周期做較多邏輯操作的情況;

下面介紹下幾種狀態值:

  • 1.STATE_EXPANDED:展開狀態,顯示完整布局;
  • 2.STATE_COLLAPED:折疊狀態,顯示設置的peekHeight高度,如果peekHeight的高度為0,則全部隱藏,與STATE_HIDDEN狀態一樣;
  • 3.STATE_HIDDEN:隱藏狀態,隱藏全部布局;
  • 4.STATE_DRAGGING:拖拽時的狀態;是個中間狀態;
  • 5.STATE_SETLLING:釋放時的狀態;是個中間狀態;
    前三個狀態值時穩定狀態,也就是說:釋放穩定后,最終會達到前三個某個狀態之一;后兩種類似ViewPager的SCROLL_STATE_DRAGGING和SCROLL_STATE_SETTLING兩種狀態值
    需要注意區別的是折疊和隱藏
  • 1.折疊
    當我們設置收起的高度app:behavior_peekHeight,在折疊的穩定狀態時,不會完全隱藏,可以通過拖動這部分布局使它進入展開狀態
  • 2.隱藏
    意味著整個底部菜單完全不可見,但是默認情況下是沒有這種狀態的,需要設置:app:behavior_hidbehavior_hideable = “true"才會出現這種狀態;

圖解如下:

狀態效果.png

二、BottomDialog的詳解

bottomDialog依賴于CoordinatorLayout和behavior,我們一般布局如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidwanga.serenitynanian.serenityproject.BottomDialogActivity">

    <!--底部菜單布局-->
    <include layout="@layout/layout_bottom_sheet_linear" />

</android.support.design.widget.CoordinatorLayout>

底部菜單布局如下:父布局必須為CoordinatorLayout,如上布局所示

  • 1.使用LinearLayout;
  • 2.使用RecyclerView
2.1 使用LinearLayout實現BottomDialog

layout_bottom_sheet_linear.xml布局如下:
**注意:
1.底部菜單必須設置:app:layout_behavior,只有設置了才能拖拽打開或隱藏,否則和普通的布局沒什么差別;
2.必須設置peekHeight高度,否則在底部菜單直接用自己的默認的高度;
3.可選設置:是否支持隱藏,如果設置了app:behavior_hideable 為false或者不設置,那么調用etState(BottomSheetBehavior.STATE_HIDDEN)沒有效果;
**

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/bottom_sheet_behavior"
    app:behavior_hideable = "true"
    app:behavior_peekHeight="66dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher_round" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:text="@string/app_name" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#999999" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher_round" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:text="@string/app_name" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#999999" />

</LinearLayout>
2.2 使用Recycler實現BottomDialog

布局如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidwanga.serenitynanian.serenityproject.BottomDialogActivity">

    <!--底部菜單布局-->

    <!--LinearLayout底部布局菜單-->
    <!--<include layout="@layout/layout_bottom_sheet_linear" />-->

    <!--RecyclerView底部布局菜單-->
    <include layout="@layout/layout_bottom_dialog_recycler"/>


</android.support.design.widget.CoordinatorLayout>

底部菜單的布局如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/bottom_dialog_recyclerview"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    app:layout_behavior="@string/bottom_sheet_behavior"
    app:behavior_peekHeight = "100dp"
    app:behavior_hideable = "true"
    >
</android.support.v7.widget.RecyclerView>

當使用這種方式,如果初始時候處于收起狀態,那么當手指上滑時,會優先讓底部菜單慢慢進入展開狀態,當完全進入展開狀態之后,開始讓列表向底部滾動。而當手指下滑時,優先讓列表向頂部滾動,當滾動到頂部之后,讓菜單從展開狀態慢慢進入到收起狀態。
使用和上面的LinearLayout一樣,不過注意一點是,在RecyclerView的adapter中的onCreateViewHolder方法中,在inflater item布局時,第二個parent參數必須設置null,否則只會顯示一個item項

  @Override
        public BottomDialogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            //注意這里的第二個參數必須為null,如果為parent時,由于嵌套的作用,只會顯示一個item項
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bottom_sheet_item, null, false);
            return new BottomDialogViewHolder(view);
        }

除此之外,我們還可以通過BottomSheetBehavior監聽底部菜單各種狀態的變化:

 //監聽底部菜單的狀態變化
        recyclerViewBottomSheetBehavior = BottomSheetBehavior.from(mRecyclerView);
        recyclerViewBottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                System.out.println("bottomSheet = [" + bottomSheet + "], newState = [" + newState + "]");
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                System.out.println("bottomSheet = [" + bottomSheet + "], slideOffset = [" + slideOffset + "]");
            }
        });

第一個回調函數用來監聽BottomSheet狀態的改變,也就是我們上面所說到的五種狀態,而onSlide回調當中的slideOffset則用來監聽底部菜單的偏移量:

  • 當處于展開狀態時,偏移量為1
  • 當處于收起狀態時,偏移量為0
  • 當處于隱藏狀態時,偏移量為-1
二、BottomSheetDialog詳解
BottomSheetDialog類繼承關系.png

從繼承關系看到BottomSheetDialog是support.v7下的擴展類,是Dialog的子類;
當我們通過setContentView方法傳入自定義布局的時候,它會將這個布局使用CoordinatorLayout包裹起來,所以當使用BottomSheetDialog的時候,底部菜單和根布局并不屬于同一個window;Dialog的根節點其實并不是通過setContentView()傳入的View,它實際上是用CoordinatorLayout把它包裝了起來,這才實現了拖動展開和隱藏的行為。

二、BottomSheetDialog類簡單的使用方式

直接看下代碼清晰明了:

private void showSharedDialog() {

        if (bottomSheetDialog == null) {
            bottomSheetDialog = new BottomSheetDialog(this);
            bottomSheetDialog.setCancelable(true);
            bottomSheetDialog.setCanceledOnTouchOutside(true);
            //這里的layout是要顯示的布局內容,里面可以放RecyclerView等
            View view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_share_dialog, null);
            bottomSheetDialog.setContentView(view);
            bottomSheetDialog.show();

            //以下設置是為了解決:下滑隱藏dialog后,再次調用show方法顯示時,不能彈出Dialog----在真機測試時不寫下面的方法也未發現問題
            View delegateView = bottomSheetDialog.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet);
            final BottomSheetBehavior<View> sheetBehavior = BottomSheetBehavior.from(delegateView);
            sheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                //在下滑隱藏結束時才會觸發
                @Override
                public void onStateChanged(@NonNull View bottomSheet, int newState) {
                    if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                        bottomSheetDialog.dismiss();
                        sheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                    }
                }
                //每次滑動都會觸發
                @Override
                public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                    System.out.println("onSlide = [" + bottomSheet + "], slideOffset = [" + slideOffset + "]");
                }
            });
        } else {
            bottomSheetDialog.show();
        }
    }

在代碼中能夠通過 BottomSheetBehavior.from(delegateView);獲得與布局相關聯的BottomSheetBehavior,它有五種狀態:

  • 1.STATE_EXPANDED:展開狀態,顯示完整布局;
  • 2.STATE_COLLAPSED:折疊狀態,顯示設置peekHeight的高度,如果peekHeight的設置為0,則全部隱藏,與STATE_HIDDEN狀態一樣;
  • 3.STATE_HIDDEN:隱藏狀態,隱藏全部布局;
  • 4.STATE_DRAGGING:拖拽時的狀態;是個中間狀態;
  • 5.STATE_SETLLING:釋放后的狀態;是個中間狀態;
    前三個是穩定的狀態,也就是釋放后,肯定會達到前三個某個狀態;

下面是bottom_sheet_share_dialog.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="?attr/actionBarSize">
        <ImageView
            android:layout_width="wrap_content"
            android:src="@mipmap/ic_launcher_round"
            android:layout_height="match_parent" />
        <TextView
            android:layout_width="match_parent"
            android:gravity="center"
            android:text="條目一"
            android:layout_height="match_parent" />
    </LinearLayout>
</LinearLayout>
三、BottomSheetDialog類復雜用法--里面使用RecyclerView

具體的看代碼:

 private void showBottomDialog() {

        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_layout, null);

        handleList(view);

        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.setCancelable(true);
        bottomSheetDialog.setCanceledOnTouchOutside(true);
        bottomSheetDialog.show();
    }

  private void handleList(View view) {
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        MyRecyclerAdapter adapter = new MyRecyclerAdapter();
        recyclerView.setAdapter(adapter);

        adapter.setData(getDatas());
        adapter.notifyDataSetChanged();
    }

    private List<String> getDatas() {
        List<String> list = new ArrayList<>();
        for (int i = 0 ;i<30 ;i++) {
            list.add("android:"+i);
        }
        return list;
    }

 public static class MyRecyclerAdapter extends RecyclerView.Adapter{

        private List<String> mData ;

        public void setData(List<String> list) {
            mData = list ;
        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.bottom_sheet_item,null));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            MyViewHolder myViewHolder = (MyViewHolder) holder;
            myViewHolder.index.setText(mData.get(position)+"");
            myViewHolder.name.setText(mData.get(position)+"");
        }

        @Override
        public int getItemCount() {
            return mData == null ? 0 :mData.size();
        }



        public static class MyViewHolder extends RecyclerView.ViewHolder{

            private TextView name ;
            private TextView index ;
            public MyViewHolder(View itemView) {
                super(itemView);
                name = (TextView) itemView.findViewById(R.id.bottom_sheet_dialog_item_name);
                index = (TextView) itemView.findViewById(R.id.bottom_sheet_dialog_item_index);
            }
        }
    }

//下面是recycler.xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">


    <RelativeLayout
        android:layout_width="match_parent"
        android:gravity="center_vertical"
        android:layout_height="?attr/actionBarSize">

        <TextView
            android:text="收藏全部"
            android:gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />
        <TextView
            android:text="播放列表(20)"
            android:gravity="center"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />
        <TextView
            android:text="清空"
            android:gravity="center"
            android:layout_alignParentRight="true"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />

    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:background="@android:color/black"
        android:layout_height="1dp"/>

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:id="@+id/recycler"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

</LinearLayout>
三、BottomSheetDialogFragment詳解

首先看下系統源碼:繼承與AppCompatDialogFragment,而AppCompatDialogFragment繼承與DialogFragment;系統重寫了onCreateDialog方法,返回一個與上面分析的BottomSheetDialog一樣,具體的使用用法和DialogFragment一樣;

/**
 * Modal bottom sheet. This is a version of {@link DialogFragment} that shows a bottom sheet
 * using {@link BottomSheetDialog} instead of a floating dialog.
 */
public class BottomSheetDialogFragment extends AppCompatDialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new BottomSheetDialog(getContext(), getTheme());
    }

}

下面是具體使用:
首先定義一個Fragment繼承BottomSheetDialogFragment,如下:

/**
 * Created by serenitynanian on 2017/5/26.
 */

public class DemoBottomSheetDialogFragment extends BottomSheetDialogFragment {

    public static DemoBottomSheetDialogFragment newInstance() {

        Bundle args = new Bundle();

        DemoBottomSheetDialogFragment fragment = new DemoBottomSheetDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //填充自己的想要的布局
        View view = inflater.inflate(R.layout.layout_bottom_sheet_linear, container, false);
        return view;
    }
}

彈出和隱藏的的實現:

public class BottomDialogFragmentActivity extends AppCompatActivity {

    private DemoBottomSheetDialogFragment demoBottomSheetDialogFragment ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bottom_dialog_fragment);

        demoBottomSheetDialogFragment = DemoBottomSheetDialogFragment.newInstance();
        //顯示dialogFragment
        showBottomSheetDialogFragment();


    }

    public void showdialog(View view) {
        showBottomSheetDialogFragment();
    }
    public void hidedialog(View view) {
        //隱藏dialogFragment
        hideBottomSheetDialogFragment();
    }

    /**
     * 顯示BottomSheetDialogFragment
     */
    private void hideBottomSheetDialogFragment() {
        if (demoBottomSheetDialogFragment == null) {
            demoBottomSheetDialogFragment.dismiss();
        }
    }

    /**
     * 顯示BottomSheetDialogFragment
     */
    private void showBottomSheetDialogFragment() {
        demoBottomSheetDialogFragment.show(getSupportFragmentManager(),"bottomSheetDialogFragment");
    }
}

四 、總結

1.其實核心就是使用CoordinatorLayout+bottom_sheet_behavior來實現拖拽;
2.使用BottomDialog時,必須使用CoordinatorLayout作為其父布局,并且需要設置bottom_sheet_behavior;
3.BottomSheetDialog和BottomSheetDialogFragment,只需要我們提供一個底部菜單的布局,在它們內部的實現當中,它再把我們傳入的布局放入到CoordinatorLayout當中,之后再把這一整個包裝好的布局作為Dialog的布局。

四 、源碼示例

github倉庫

相關內容:

一、CoordinatorLayout的梳理與使用

二、Toolbar的梳理與使用

三、TextInputLayout的梳理與使用

四、FloatingActionButton的梳理與使用

五、Snackbar的梳理與使用

六、CardView的梳理與使用

七、BottomSheetDialog的梳理與使用

八、TabLayout的梳理與使用

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

推薦閱讀更多精彩內容