BottomSheet是一个 com.android.support:design包里面的一个可以可拖动的控件,从底部往上滑动展现更多内容。
用的时候需要的注意:配合协调者布局:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
layout="@layout/bottom_sheet"/>
</android.support.design.widget.CoordinatorLayout>
bottom_sheet布局里面的内容也很简单:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/ll_bottom_sheet"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#f99"
android:orientation="vertical"
app:behavior_hideable="true"
app:behavior_peekHeight="80dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:gravity="center"
android:text="bottom_sheet_peek" />
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:gravity="center"
android:text="内容" />
</LinearLayout>
注意这几个表示:
// behavior_hideable:定义是否能通过下滑手势收起Bottom Sheet。
app:behavior_hideable="true"
// behavior_peekHeight:定义可见部分的高度。
app:behavior_peekHeight="80dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
最后还有一个代码中怎样设置和监听用的时候需要注意的:
private void initBottomSheet() {
// 这个地方注意添加behavior之后不要再include上添加id了,
// 否则你通过 findviewbyId(inclue id).findViewById(子view的id)会报这个 View 为空的空指针异常
LinearLayout view = findViewById(R.id.ll_bottom_sheet);
BottomSheetBehavior<LinearLayout> bottomSheetBehavior = BottomSheetBehavior.from(view);
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
bottomSheetBehavior.setPeekHeight(600);
bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View view, int i) {
Log.i(TAG,"i=="+i);
}
@Override
public void onSlide(@NonNull View view, float v) {
Log.i(TAG,"v=="+v);
}
});
}
}
BottomSheet的五种状态:
STATE_DRAGGING:手指在BottomSheet上下拖动从而使得布局跟着上下移动。
STATE_SETTLING:当手指抬起之后,会根据当前的偏移量,决定是要将BottomSheet收起还是展开。
这两种属于中间态,类似于ViewPager的SCROLL_STATE_DRAGGING和SCROLL_STATE_SETTLING。
--------------------------------------
STATE_EXPANDED:展开。
STATE_COLLAPSED:收起。
STATE_HIDDEN:隐藏。
这三种属于稳定态,当BottomSheet稳定下来,最终都会恢复到上面三种状态之一,展开很容易理解,需要区别的是收起和隐藏:
隐藏:意味着整个底部布局完全不可见,默认情况下没有这种状态,需要设置app:behavior_hideable="true"
收起:我们可以设置收起时的高度,让它仍然部分可见,并可以通过拖动这部分布局让它进入到展开状态,收起时的高度通过
app:behavior_peekHeight设置。