在 Android 開發中,常見的側滑菜單(如 QQ、微信側邊欄)在滑動時,菜單上半部分的背景圖片保持固定不變,只有下半部分內容跟隨滑動。這種效果如何實現?
關鍵在於將側滑菜單的佈局拆分為兩部分:
在 DrawerLayout 的側滑視圖中,使用 FrameLayout 作為根佈局,底層放一個 ImageView(設置 android:scaleType="centerCrop"),上層放一個 RecyclerView 或 ListView 承載菜單項目。由於 DrawerLayout 只移動整個側滑視圖,背景圖會跟著移動,因此需要在滑動監聽器中動態調整背景圖的位置,使其視覺上保持固定。
利用 Material Design 組件,將側滑菜單設計為一個 NavigationView,其頭部佈局使用 CollapsingToolbarLayout 包裹 ImageView,設置 app:layout_collapseMode="parallax" 和 app:layout_collapseParallaxMultiplier="0.5",即可實現背景圖視差固定效果。
<androidx.drawerlayout.widget.DrawerLayout ...>
<!-- 主內容 -->
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:contentScrim="?attr/colorPrimary"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.5">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/nav_header_bg" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<!-- 菜單列表 -->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/nav_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="200dp" />
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
GitHub 上有許多成熟的側滑菜單庫已實現此效果,如:
側滑菜單背景固定的核心是「背景層與內容層分離」,配合視差滾動或手動位置修正。建議使用 CollapsingToolbarLayout 實現,代碼量少、效果佳、符合 Material Design 規範。
ClassNotFoundException: weka.classifiers.Classifier:缺少依賴 JAR 排查
Eclipse 開發 JSP 中文亂碼的三層解決方案:工作空間編碼、web.xml 過濾器、頁面 pageEncoding
Java 字符串內部機制深度解析:編譯期優化、常量池與 new String() 的區別
Java 實體類基礎:People 類屬性封裝與 Getter/Setter 模式解析
Java ImageIO.read 返回 null:Base64 解碼後流位置未重置導致無法識別圖片格式
Redis 伺服器記憶體壓力大?新手必看的擴容與配置指南
Linux C 語言 fork() 進程調度順序不確定性分析