七、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阅读 156,907评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,546评论 1 289
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,705评论 0 238
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,624评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,940评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,371评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,672评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,396评论 0 195
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,069评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,350评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,876评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,243评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,847评论 3 231
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,004评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,755评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,378评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,266评论 2 259

推荐阅读更多精彩内容