需求:App 啟動時底部佈局僅露出一部分(如節日節氣卡片),用戶向上拖拽可展開完整內容(黃歷、節氣詳情),類似 365日曆、Google Maps 底部面板效果。這在 Material Design 中稱為 BottomSheet。
implementation 'com.google.android.material:material:1.9.0'<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 主內容 -->
<FrameLayout android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- BottomSheet -->
<LinearLayout
android:id="@+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="300dp"
android:orientation="vertical"
android:background="@android:color/white"
app:behavior_hideable="false"
app:behavior_peekHeight="120dp"
app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="節日節氣摘要"
android:padding="16dp"
android:gravity="center"/>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#eee"/>
<RecyclerView android:id="@+id/detail_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
BottomSheetBehavior behavior = BottomSheetBehavior.from(findViewById(R.id.bottom_sheet));
// 設置狀態:STATE_COLLAPSED(摺疊)、STATE_EXPANDED(展開)、STATE_HIDDEN(隱藏)
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
// 監聽滑動
behavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override public void onStateChanged(@NonNull View bottomSheet, int newState) { }
@Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { }
});
原理:在 onTouchEvent 中記錄 ACTION_DOWN Y 座標,ACTION_MOVE 計算位移,動態更新底部佈局 translationY 或 LayoutParams.height。需自行處理惯性滑動、邊界彈回、狀態機,代碼量大且易出 Bug,**不推薦**新項目使用。
app:behavior_peekHeight:摺疊時露出的高度(如 120dp)。app:behavior_hideable:是否允許下滑隱藏(false 保持常駐)。app:behavior_skipCollapsed:展開時是否跳過摺疊態直接全開。若需模態彈出(如分享面板、篩選器),繼承 BottomSheetDialogFragment,在 setupDialog 中設置佈局,自帶動畫、背景遮罩、鍵盤處理,極其方便。
使用 BottomSheetBehavior 可用最少代碼實現專業級交互,符合 Material Design 規範,是現代 Android 開發的標準選擇。