接着第一天的项目,继续往前推进。
1. 底部导航栏的设置
2. 引入ARouter组件。
底部导航栏功能实现
1. res下创建menu,新建xml文件内容如下
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/navigation_home"
android:icon="@drawable/ic_home"
android:title="@string/menu_merch_first" />
<item
android:id="@+id/navigation_order"
android:icon="@drawable/ic_order"
android:title="@string/menu_merch_second" />
<item
android:id="@+id/navigation_user"
android:icon="@drawable/ic_user"
android:title="@string/menu_merch_third" />
</menu>
2. res下创建navigation,新建文件内容如下
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_navigation"
app:startDestination="@+id/navigation_home">
<fragment
android:id="@+id/navigation_home"
android:name="com.duoduomi.app.page.merch.HomeFragment"
tools:layout="@layout/fragment_home" />
<fragment
android:id="@+id/navigation_order"
android:name="com.duoduomi.app.page.merch.OrderFragment"
tools:layout="@layout/fragment_order" />
<fragment
android:id="@+id/navigation_user"
android:name="com.duoduomi.app.page.merch.UserFragment"
tools:layout="@layout/fragment_user" />
</navigation>
3. 布局文件XML中设置如下
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:background="?android:attr/windowBackground"
app:labelVisibilityMode="labeled"
app:itemIconTint="@drawable/bottom_nav_color_selector"
app:itemTextColor="@drawable/bottom_nav_color_selector"
app:itemRippleColor="@null"
app:itemBackground="@null"
app:menu="@menu/bottom_navigation_menu" />
<!-- 页面中显式fragment的容器-->
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@id/bottom_navigation"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/mobile_navigation" />
4. activity文件设置
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
NavController controller = Navigation.findNavController(this, R.id.nav_host_fragment);
//在选择菜单时调用,当目的地更改时,BottomNavigationView中的选定项将自动更新
NavigationUI.setupWithNavController(bottomNavigationView, controller);
5. 效果如下。