首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android 側滑菜單背景圖固定不變的實現原理與方案

     編輯:程式設計疑難解答

問題背景

在 Android 開發中,常見的側滑菜單(如 QQ、微信側邊欄)在滑動時,菜單上半部分的背景圖片保持固定不變,只有下半部分內容跟隨滑動。這種效果如何實現?

核心思路

關鍵在於將側滑菜單的佈局拆分為兩部分:

  1. 固定背景層:放置在最底層,包含背景圖片(ImageView),不參與滑動動畫。
  2. 滑動內容層:包含菜單列表、用戶信息等可滑動內容,放在背景層之上,隨手勢滑動。

實現方案

方案一:使用 DrawerLayout + 自定義佈局

在 DrawerLayout 的側滑視圖中,使用 FrameLayout 作為根佈局,底層放一個 ImageView(設置 android:scaleType="centerCrop"),上層放一個 RecyclerView 或 ListView 承載菜單項目。由於 DrawerLayout 只移動整個側滑視圖,背景圖會跟著移動,因此需要在滑動監聽器中動態調整背景圖的位置,使其視覺上保持固定。

方案二:使用 CoordinatorLayout + CollapsingToolbarLayout(推薦)

利用 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 規範。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved