需求
点击界面按钮,从底部弹出个布局,点击空白消失.
效果图

分析
可以使用自定义对话框来实现,但这里要采用协调布局来做.
xml文件
<android.support.design.widget.CoordinatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/bt_show"
android:text="底部弹出布局"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="@+id/rl_botomo"
app:layout_behavior="@string/bottom_sheet_behavior"
android:background="@color/top_bar"
android:layout_width="match_parent"
android:layout_height="200dp">
<TextView
android:gravity="center"
android:text="底部布局"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
最外层用协调布局包裹,最底层布局配置 app:layout_behavior="@string/bottom_sheet_behavior" 属性
逻辑实现
点击button,弹出布局
把底部控件放入BottomSheetBehavior,并调用setPeekHeight方法,在点击事件中设置相应的属性
bottomSheetBehavior = BottomSheetBehavior.from(findViewById(R.id.rl_botomo));
bottomSheetBehavior.setPeekHeight(0);
button = (Button) findViewById(R.id.bt_show);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
}
});
点击空白,隐藏布局
这里使用的是界面手势识别器,可以识别界面的单击事件,来给Behavior设置相应的属性来控制隐藏.
gestureDetector = new GestureDetector(this, new OnVideoGestureListener());
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
private class OnVideoGestureListener extends GestureDetector.SimpleOnGestureListener {
//处理单击事件 -- 控制面板的显示or隐藏
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED){
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
return super.onSingleTapConfirmed(e);
}
}
总结
手势识别器的使用
BottomSheetBehavior的简单应用
网友评论