Android Modal Bottom Sheets

之前介紹過BottomSheets的兩種Type - Modal Bottom Sheets & Persistent Bottom Sheets

請參考:Android - Bottom Sheets

此篇來介紹如何設計 Modal Bottom Sheets (BottomSheetDialog)

Step 1: 新增 layout xml

在 res/layout 中新增 layout xml : bottom_sheet_dialog.xml

裡面包含一個TextView和RecyclerView (顯示球員名單)

bottom_sheet_dialog.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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:id="@+id/bottom_sheet_dialog"
android:layout_width="match_parent"
android:layout_height="444dp"
android:elevation="8dp"
android:orientation="vertical"
android:padding="5dp"
android:background="@color/colorPrimary"
app:layout_behavior="@string/bottom_sheet_behavior">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Players"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="@color/colorAccent"/>

<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp" />
</LinearLayout>

Step 2: 新增BottomSheetDialog

在程式中設置BottomSheetDialog

MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
ArrayList<Player> players = generatePlayers();
PlayerAdapter adapter = new PlayerAdapter(players);

View view = getLayoutInflater().inflate(R.layout.bottom_sheet_dialog, null);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);

mBottomSheetDialog = new BottomSheetDialog(this);
mBottomSheetDialog.setContentView(view);

mPlayerBehavior = BottomSheetBehavior.from((View) view.getParent());
mPlayerBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);

在此必須注意 BottomSheetBehavior.from((View) view.getParent());
必須在BottomSheetDialog.setContentView(view) 之後.
否則會有NULL Exception發生.

每次使用BottomSheetDialog.show()之前, 需要使用BottonSheetBehavior.setState 重新設定高度

MainActivity.java
1
2
mPlayerBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
mBottomSheetDialog.show();

若無設定BottonSheetBehavior.setState的話, 當使用拖拉將BottomSheetDialog收起後, 下次呼叫BottomSheetDialog.show()時, 會出現暗掉卻無看見BottomSheetDialog的情況.

原因是BottomSheetDialog有出現, 但是位置在畫面下方.

由於在此範例中BottomSheetDialog為全域變數, 只有在程式開始時 OnCreate() 做初始設定.

之後只呼叫BottomSheetDialog.show來顯示, 但顯示位置為先前Dialog在畫面中的高度.

所以每當顯示時, 需要先重新設置高度.

作者

Nick Lin

發表於

2016-06-06

更新於

2023-01-18

許可協議


評論