Android之framework修改底部导航栏NavigationBar动态显示和隐藏

本文介绍了一种在Android中动态隐藏和显示NavigationBar的方法。通过在SystemUI模块添加按钮并实现点击事件来隐藏NavigationBar,并通过添加从屏幕底部向上的滑动手势来重新显示NavigationBar。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       大家都知道,Android从3.0版本开始就加入了NavigationBar,主要是为那些没有实体按键的设备提供虚拟按键,但是,它始终固定在底部,占用48dp的像素高度,尽管从android 4.4开始可以全透明,使用这一部分像素,但三个按钮始终悬浮在屏幕上,这对于有强迫症的朋友来说是无法忍受的。因此,本文的目的就是修改framework部分代码,可以动态隐藏和显示NavigationBar,同时又尽量不影响系统的正常。

主要思路:

在NavigationBar的布局左部加入一个Button(在SystemUI模块实现),点击隐藏NavigationBar,即将NavigationBar从WindowManager中移除掉。需要的时候,通过一个从屏幕底部向上的滑动手势(在policy模块实现)调出NavigationBar。如下两图对比所示:一张为移除前,另一张为移除后。


具体实现:

①.增加按钮实现动态隐藏,主要修改在frameworks/base/packages/SystemUI模块,首先我们增加一个按钮,主要修改

frameworks/base/packages/SystemUI/res/layout/navigation_bar.xml文件,图片资源和字符串我就不提了,具体如下:

diff --git a/frameworks/base/packages/SystemUI/res/layout/navigation_bar.xml b/frameworks/base/packages/SystemUI/res/layout/navigation_bar.xml
index 16027d9..326aafc 100644
--- a/frameworks/base/packages/SystemUI/res/layout/navigation_bar.xml
+++ b/frameworks/base/packages/SystemUI/res/layout/navigation_bar.xml
@@ -42,12 +42,28 @@
             >

             <!-- navigation controls -->
+           <!--BEGIN liweiping
             <View
                 android:layout_width="40dp"
                 android:layout_height="match_parent"
                 android:layout_weight="0"
                 android:visibility="invisible"
                 />
+           -->
+            <FrameLayout
+                android:layout_width="@dimen/navigation_extra_key_width"
+                android:layout_height="match_parent"
+                android:layout_weight="0" >
+                <ImageButton
+                    android:id="@+id/hide_bar_btn"
+                    android:layout_width="@dimen/navigation_extra_key_width"
+                    android:layout_height="match_parent"
+                    android:contentDescription="@string/accessibility_hide"
+                    android:src="@drawable/ic_sysbar_hide"
+                     />
+
+            </FrameLayout>
+           <!--END liweiping -->
             <com.android.systemui.statusbar.policy.KeyButtonView android:id="@+id/back"
                 android:layout_width="@dimen/navigation_key_width"
                 android:layout_height="match_parent"
@@ -246,12 +262,28 @@
                 android:layout_weight="0"
                 android:contentDescription="@string/accessibility_back"
                 />
+           <!--BEGIN liweiping
             <View
                 android:layout_height="40dp"
                 android:layout_width="match_parent"
                 android:layout_weight="0"
                 android:visibility="invisible"
                 />
+           -->
+            <FrameLayout
+                android:layout_weight="0"
+                android:layout_width="match_parent"
+                android:layout_height="40dp" >
+
+                <ImageButton
+                    android:id="@+id/hide_bar_btn"
+                    android:layout_width="match_parent"
+                    android:layout_height="40dp"
+                    android:contentDescription="@string/accessibility_hide"
+                    android:src="@drawable/ic_sysbar_hide_land"
+                     />
+            </FrameLayout>
+           <!--END liweiping -->
         </LinearLayout>

         <!-- lights out layout to match exactly -->

接下来修改frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java,为按钮提供一个接口,具体如下:

diff --git a/frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java b/frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
index 88e71e2..7545984 100644
--- a/frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
+++ b/frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
@@ -45,6 +45,7 @@ import com.android.systemui.R;
 import com.android.systemui.statusbar.BaseStatusBar;
 import com.android.systemui.statusbar.DelegateViewHelper;
 import com.android.systemui.statusbar.policy.DeadZone;
+import com.android.systemui.statusbar.policy.KeyButtonRipple;
 import com.android.systemui.statusbar.policy.KeyButtonView;

 import java.io.FileDescriptor;
@@ -265,6 +266,13 @@ public class NavigationBarView extends LinearLayout {
     public View getImeSwitchButton() {
         return mCurrentView.findViewById(R.id.ime_switcher);
     }
+    //BEGIN liweiping
+    public View getHideBarButton() {
+       View view = mCurrentView.findViewById(R.id.hide_bar_btn);
+       view.setBackground(new KeyButtonRipple(getContext(), view));
+        return view;
+    }
+    //END liweiping

     private void getIcons(Resources res) {
         mBackIcon = res.getDrawable(R.drawable.ic_sysbar_back);
@@ -412,7 +420,6 @@ public class NavigationBarView extends LinearLayout {
         mCurrentView = mRotatedViews[Surface.ROTATION_0];

         getImeSwitchButton().setOnClickListener(mImeSwitcherClickListener);
-
         updateRTLOrder();
     }



最后便是在frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java实现点击事件了:

+    private final OnClickListener mHideBarClickListener = new OnClickListener() {
+        @Override
+        public void onClick(View view) {
+           Log.i("way", "mHideBarClickListener  onClick...");
+           removeNavigationBar();
+        }
+    };

+    private void removeNavigationBar() {
+        if (DEBUG) Log.d(TAG, "removeNavigationBar: about to remove " + mNavigationBarView);
+        if (mNavigationBarView == null) return;
+
+        mWindowManager.removeView(mNavigationBarView);
+        mNavigationBarView = null;
+    }



到此,隐藏NavigationBar告一段落了。


②.接下来便是显示NavigationBar,这个修改相对复杂一点。因为此时NavigationBar处于不可见状态,我们无法通过增加按钮的方式让其显示,但是我们知道,状态栏下拉通过手势向下滑动即可。因此很容易便想到通过手势从屏幕底部向上滑动来显示NavigationBar。我的想法是在policy模块中增加一个接口,通过frameworks/base/services/core/java/com/android/server/statusbar/StatusBarManagerService.java服务传递到状态栏中,从而触发显示NavigationBar事件。

也许大家会有疑问,为什么是在policy模块修改?其实我这只是一种解决方案,因为我知道

frameworks/base/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java 有现成的手势滑动接口。其实你也可以SystemUI中增加一个这样的事件,我们需要的就是这么一个触发事件。

PhoneWindowManager.java的修改主要是实现onSwipeFromBottom(竖屏时)和onSwipeFromRight(横屏时)两个接口,然后调用showNavigationBar,在showNavigationBar函数中,我们调用StatusBarManagerService服务中的showNavigationBar函数,具体如下:

diff --git a/frameworks/base/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java b/frameworks/base/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
index bb53e12..907202d 100644
--- a/frameworks/base/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/frameworks/base/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -1241,13 +1241,27 @@ public class PhoneWindowManager implements WindowManagerPolicy {
                     public void onSwipeFromBottom() {
                         if (mNavigationBar != null && mNavigationBarOnBottom) {
                             requestTransientBars(mNavigationBar);
+                            Log.i("way", "onSwipeFromBottom... mNavigationBar != null && mNavigationBarOnBottom");
                         }
+                        //BEGIN liweiping
+                        else{
+                           Log.i("way", "onSwipeFromBottom...");
+                           showNavigationBar();
+                        }
+                        //END liweiping
                     }
                     @Override
                     public void onSwipeFromRight() {
                         if (mNavigationBar != null && !mNavigationBarOnBottom) {
                             requestTransientBars(mNavigationBar);
+                            Log.i("way", "onSwipeFromRight... mNavigationBar != null && !mNavigationBarOnBottom");
+                        }
+                        //BEGIN liweiping
+                        else{
+                           Log.i("way", "onSwipeFromRight...");
+                           showNavigationBar();
                         }
+                        //END liweiping
                     }
                     @Override
                     public void onDebug() {
@@ -1293,7 +1307,24 @@ public class PhoneWindowManager implements WindowManagerPolicy {
             goingToSleep(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
         }
     }
-
+    //BEGIN liweiping
+    private void showNavigationBar(){
+        mHandler.post(new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    IStatusBarService statusbar = getStatusBarService();
+                    if (statusbar != null) {
+                        statusbar.showNavigationBar();
+                    }
+                } catch (RemoteException e) {
+                    // re-acquire status bar service next time it is needed.
+                    mStatusBarService = null;
+                }
+            }
+        });
+    }
+    //END liweiping
     private void updateKeyAssignments() {
         final boolean hasMenu = (mDeviceHardwareKeys & KEY_MASK_MENU) != 0;
         final boolean hasHome = (mDeviceHardwareKeys & KEY_MASK_HOME) != 0;



这时事件传递到了StatusBarManagerService中,我们来看看StatusBarManagerService.java如何实现showNavigationBar:

diff --git a/frameworks/base/services/core/java/com/android/server/statusbar/StatusBarManagerService.java b/frameworks/base/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
index f85e2d9..3f75840 100644
--- a/frameworks/base/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
+++ b/frameworks/base/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
@@ -366,6 +366,27 @@ public class StatusBarManagerService extends IStatusBarService.Stub {
                     "WindowManager.LayoutParams");
         }
     }
+    //BEGIN liweiping
+    @Override
+    public void showNavigationBar() {
+        enforceStatusBar();
+
+        android.util.Log.d("way", TAG + " showNavigationBar...");
+
+        synchronized(mLock) {
+            mHandler.post(new Runnable() {
+                    public void run() {
+                        if (mBar != null) {
+                            try {
+                                mBar.showNavigationBar();
+                            } catch (RemoteException ex) {
+                            }
+                        }
+                    }
+                });
+        }
+    }
+    //END liweiping

     private void updateUiVisibilityLocked(final int vis, final int mask) {
         if (mSystemUiVisibility != vis) {



从上述代码可以看出,StatusBarManagerService只是起到一个传递作用,将消息传递到StatusBar中,最终的实现是在SystemUI模块的frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java,如下所示:

diff --git a/frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java b/frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
index 9db875f..4f24b6e 100644
--- a/frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
+++ b/frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
@@ -56,6 +56,7 @@ public class CommandQueue extends IStatusBar.Stub {
     private static final int MSG_BUZZ_BEEP_BLINKED          = 15 << MSG_SHIFT;
     private static final int MSG_NOTIFICATION_LIGHT_OFF     = 16 << MSG_SHIFT;
     private static final int MSG_NOTIFICATION_LIGHT_PULSE   = 17 << MSG_SHIFT;
+    private static final int MSG_SHOW_NAVIGATIONBAR   = 18 << MSG_SHIFT;//ADD liweiping

     public static final int FLAG_EXCLUDE_NONE = 0;
     public static final int FLAG_EXCLUDE_SEARCH_PANEL = 1 << 0;
@@ -83,6 +84,7 @@ public class CommandQueue extends IStatusBar.Stub {
         public void animateCollapsePanels(int flags);
         public void animateExpandSettingsPanel();
         public void setSystemUiVisibility(int vis, int mask);
+        public void showNavigationBar();//ADD liweiping
         public void topAppWindowChanged(boolean visible);
         public void setImeWindowStatus(IBinder token, int vis, int backDisposition,
                 boolean showImeSwitcher);
@@ -154,6 +156,14 @@ public class CommandQueue extends IStatusBar.Stub {
             mHandler.obtainMessage(MSG_SET_SYSTEMUI_VISIBILITY, vis, mask, null).sendToTarget();
         }
     }
+    //BEGIN liweiping
+    public void showNavigationBar() {
+        synchronized (mList) {
+            mHandler.removeMessages(MSG_SHOW_NAVIGATIONBAR);
+            mHandler.sendEmptyMessage(MSG_SHOW_NAVIGATIONBAR);
+        }
+    }
+    //END liweiping

     public void topAppWindowChanged(boolean menuVisible) {
         synchronized (mList) {
@@ -283,6 +293,11 @@ public class CommandQueue extends IStatusBar.Stub {
                 case MSG_SET_SYSTEMUI_VISIBILITY:
                     mCallbacks.setSystemUiVisibility(msg.arg1, msg.arg2);
                     break;
+                //BEGIN liweiping
+                case MSG_SHOW_NAVIGATIONBAR:
+                   mCallbacks.showNavigationBar();
+                   break;
+                //END liweiping
                 case MSG_TOP_APP_WINDOW_CHANGED:
                     mCallbacks.topAppWindowChanged(msg.arg1 != 0);
                     break;



CommandQueue.java收到了这个消息之后,又回调给了base/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java,绕了大半天,消息终于回来了,我们就是需要在PhoneStatusBar.java实现显示NavigationBar的函数了:

+    @Override // CommandQueue
+    public void showNavigationBar() {
+       Log.i("way", TAG + " showNavigationBar...");
+       forceAddNavigationBar();
+    }

+    private void forceAddNavigationBar() {
+        // If we have no Navbar view and we should have one, create it
+        if (mNavigationBarView != null) {
+            return;
+        }
+
+        mNavigationBarView =
+                (NavigationBarView) View.inflate(mContext, R.layout.navigation_bar, null);

+        mNavigationBarView.setDisabledFlags(mDisabled);
+        mNavigationBarView.setBar(this);
+        addNavigationBar(true); // dynamically adding nav bar, reset System UI visibility!
+    }

+    private void prepareNavigationBarView(boolean forceReset) {
+        mNavigationBarView.reorient();
+        mNavigationBarView.getRecentsButton().setOnClickListener(mRecentsClickListener);
+        mNavigationBarView.getRecentsButton().setOnTouchListener(mRecentsPreloadOnTouchListener);
+        mNavigationBarView.getRecentsButton().setLongClickable(true);
+        mNavigationBarView.getRecentsButton().setOnLongClickListener(mLongPressBackRecentsListener);
+        mNavigationBarView.getBackButton().setLongClickable(true);
+        mNavigationBarView.getBackButton().setOnLongClickListener(mLongPressBackRecentsListener);
+        mNavigationBarView.getHomeButton().setOnTouchListener(mHomeActionListener);
+        mNavigationBarView.getHideBarButton().setOnClickListener(mHideBarClickListener);//ADD liweiping
+
+        if (forceReset) {
+            // Nav Bar was added dynamically - we need to reset the mSystemUiVisibility and call
+            // setSystemUiVisibility so that mNavigationBarMode is set to the correct value
+           Log.i("way", "prepareNavigationBarView mNavigationBarMode = "+ mNavigationBarMode + " mSystemUiVisibility = " + mSystemUiVisibility + " mNavigationIconHints = " + mNavigationIconHints);
+           mNavigationBarMode = 0;
+           
+            int newVal = mSystemUiVisibility;
+            mSystemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
+            setSystemUiVisibility(newVal, /*SYSTEM_UI_VISIBILITY_MASK*/0xffffffff);
+            int hints = mNavigationIconHints;
+            mNavigationIconHints = 0;
+            setNavigationIconHints(hints);
+            topAppWindowChanged(mShowMenu);
+        }
+
+        updateSearchPanel();
+    }
+
+    // For small-screen devices (read: phones) that lack hardware navigation buttons
+    private void addNavigationBar(boolean forceReset) {
+        if (DEBUG) Log.v(TAG, "addNavigationBar: about to add " + mNavigationBarView);
+        if (mNavigationBarView == null) return;
+
+        prepareNavigationBarView(forceReset);
+
+        mWindowManager.addView(mNavigationBarView, getNavigationBarLayoutParams());
+    }
+    //END liweiping


需要注意的是:

①显示NavigationBar时,需要重新实例化一次NavigationBarView,我之前有试过移除NavigationBarView后未置空,下次添加时直接使用,会出现状态栏重启的情况,具体原因未知,log显示动画播放错误之类。

②重新添加NavigationBarView时需要恢复NavigationBarView之前的状态,比如说隐藏前时是透明的、显示输入法按钮、菜单键等等。

③本文是在Android5.0的代码上修改的,其他版本未验证。

④本文仅是提供一种思路,并非最优方案。

⑤转载请注明出处:http://blog.youkuaiyun.com/way_ping_li



<think>我们正在使用Jetpack Compose实现底部导航栏。根据引用内容,我们可以使用Scaffold、NavigationBarNavigationBarItem组件来实现。此外,我们还需要一个导航控制器(NavController)来管理不同目的地之间的切换。 步骤: 1. 添加依赖:确保在build.gradle文件中添加了必要的Compose Navigation依赖。 2. 定义页面枚举或密封类:用于表示底部导航栏的各个目的地。 3. 创建NavHostController:用于控制导航。 4. 创建可组合函数:每个目的地对应的界面。 5. 使用Scaffold布局:其中bottomBar参数设置为我们的导航栏。 6. 在导航栏中使用NavigationBarNavigationBarItem。 以下是一个简单的实现示例: 首先,在build.gradle中添加依赖(如果尚未添加): ```kotlin dependencies { implementation "androidx.navigation:navigation-compose:2.7.7" // 请使用最新版本 implementation "androidx.compose.material3:material3:1.1.2" // 如果使用material3 } ``` 然后,在代码中实现: ```kotlin import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.res.stringResource import androidx.navigation.NavDestination.Companion.hierarchy import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController // 步骤1:定义导航目的地(使用密封类或枚举) sealed class Screen(val route: String, val title: String, val icon: Int) { object Home : Screen("home", "Home", R.drawable.ic_home) object Search : Screen("search", "Search", R.drawable.ic_search) object Profile : Screen("profile", "Profile", R.drawable.ic_profile) } @Composable fun MainScreen() { val navController = rememberNavController() // 当前选中的目的地 val currentBackStack by navController.currentBackStackEntryAsState() val currentDestination = currentBackStack?.destination // 底部导航栏应该显示的目的地列表 val screens = listOf(Screen.Home, Screen.Search, Screen.Profile) Scaffold( bottomBar = { NavigationBar { screens.forEach { screen -> // 为每个目的地创建导航项 NavigationBarItem( icon = { Icon(painterResource(screen.icon), contentDescription = screen.title) }, label = { Text(screen.title) }, selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true, onClick = { // 点击时导航到该目的地,并弹出到该目的地栈的顶部 navController.navigate(screen.route) { popUpTo(navController.graph.findStartDestination().id) { saveState = true } launchSingleTop = true restoreState = true } } ) } } } ) { innerPadding -> // 设置NavHost,将内边距传递给各个页面 NavHost( navController = navController, startDestination = Screen.Home.route, modifier = Modifier.padding(innerPadding) ) { composable(Screen.Home.route) { HomeScreen() } composable(Screen.Search.route) { SearchScreen() } composable(Screen.Profile.route) { ProfileScreen() } } } } // 示例页面 @Composable fun HomeScreen() { Text("Home Screen") } @Composable fun SearchScreen() { Text("Search Screen") } @Composable fun ProfileScreen() { Text("Profile Screen") } ``` 说明: - 我们使用`Scaffold`来搭建页面框架,并在`bottomBar`参数中传入`NavigationBar`。 - `NavigationBar`内部包含多个`NavigationBarItem`,每个对应一个目的地。 - 使用`NavController`来管理导航状态,通过`currentBackStackEntryAsState`来获取当前的导航栈,从而确定当前选中的目的地。 - 当点击`NavigationBarItem`时,我们使用`navController.navigate`进行导航,并配置弹出行为(例如,弹出到起始目的地,并保存状态等)。 - `NavHost`定义了各个目的地的可组合函数,它会根据当前的目的地显示相应的内容。 注意:图标资源(如`R.drawable.ic_home`)需要你自己在res/drawable中添加。 以上代码实现了基本的底部导航栏功能。在实际应用中,你可能需要根据设计调整样式交互。 引用说明: 根据引用[1]引用[4],我们使用了`Scaffold`、`NavigationBar``NavigationBarItem`,这与引用中的描述一致。同时,我们使用了导航控制器来管理导航状态,这与引用[3]中提到的导航方式类似,但Compose的方式更为简洁。 引用[1]: Android JetPack Compose实现底部导航栏,material3。 Android JetPack Compose实现底部导航栏,material3 1.Scaffold + NavigationBar + NavigationBarItem2.案例实现 [^1] 引用[4]: JetPack Compose安卓开发之底部导航Tabbar。Navigation.kt 枚举 package com.weimin.strollerapp.components.tabbar import com.weimin.strollerapp.R enum class Navigation( val selectedIcon: Int, val unSelectedIcon: Int, val titleTextId: Int, val route: String, ) { ... } [^4] 因此,我们通过上述代码实现了底部导航栏。 注意:本示例使用的是Material3组件,如果你使用Material2,组件名称可能略有不同(例如,使用`BottomNavigation``BottomNavigationItem`)。 如果你需要更多定制(如动画、不同样式的导航栏等),可以参考Compose官方文档。</think>### 在 Android Jetpack Compose 中实现底部导航栏 在 Jetpack Compose 中实现底部导航栏需要以下核心组件: 1. **`NavController`**:管理导航状态 2. **`NavHost`**:显示当前目的地 3. **`NavigationBar`** (Material3):底部导航栏容器 4. **`NavigationBarItem`**:导航项 #### 完整实现代码 ```kotlin // 1. 定义导航目的地 sealed class Screen(val route: String, @StringRes val title: Int, val icon: Int) { object Home : Screen("home", R.string.home, R.drawable.ic_home) object Search : Screen("search", R.string.search, R.drawable.ic_search) object Profile : Screen("profile", R.string.profile, R.drawable.ic_profile) } @Composable fun MainScreen() { val navController = rememberNavController() val items = listOf(Screen.Home, Screen.Search, Screen.Profile) // 获取当前路由 val backStackEntry by navController.currentBackStackEntryAsState() val currentRoute = backStackEntry?.destination?.route Scaffold( bottomBar = { NavigationBar { items.forEach { screen -> NavigationBarItem( icon = { Icon(painterResource(id = screen.icon), contentDescription = null) }, label = { Text(stringResource(screen.title)) }, selected = currentRoute == screen.route, onClick = { navController.navigate(screen.route) { // 导航配置 popUpTo(navController.graph.findStartDestination().id) { saveState = true } launchSingleTop = true restoreState = true } } ) } } } ) { innerPadding -> NavHost( navController = navController, startDestination = Screen.Home.route, modifier = Modifier.padding(innerPadding) ) { composable(Screen.Home.route) { HomeScreen() } composable(Screen.Search.route) { SearchScreen() } composable(Screen.Profile.route) { ProfileScreen() } } } } // 示例页面组件 @Composable fun HomeScreen() { Text("首页内容", modifier = Modifier.fillMaxSize().wrapContentSize()) } @Composable fun SearchScreen() { Text("搜索页面", modifier = Modifier.fillMaxSize().wrapContentSize()) } @Composable fun ProfileScreen() { Text("个人资料", modifier = Modifier.fillMaxSize().wrapContentSize()) } ``` #### 关键配置说明: 1. **导航状态管理**: - `rememberNavController()` 创建导航控制器 - `currentBackStackEntryAsState()` 跟踪当前路由状态 2. **导航栏配置**: - `NavigationBar` 创建 Material3 风格的底部栏 - 每个 `NavigationBarItem` 对应一个目的地 - `selected` 参数根据当前路由高亮显示 3. **导航行为**: ```kotlin navController.navigate(screen.route) { popUpTo(navController.graph.findStartDestination().id) { saveState = true } launchSingleTop = true restoreState = true } ``` 这段配置确保: - 返回栈只保留起始目的地 - 避免创建重复实例 - 保存/恢复页面状态[^1][^3] 4. **页面容器**: - `NavHost` 根据当前路由显示对应组件 - 使用 `Scaffold` 的 `innerPadding` 避免内容被导航栏遮挡 #### 依赖配置(build.gradle) ```gradle dependencies { implementation "androidx.navigation:navigation-compose:2.7.7" // 最新稳定版 implementation "androidx.compose.material3:material3:1.2.1" } ``` > **注意**:Material3 的 `NavigationBar` 替代了旧版的 `BottomNavigation`,提供更现代化的设计[^1][^2]。如需添加动画效果,可在页面切换时使用 `AnimatedContent` 或 `Crossfade`。
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值