这篇主要介绍navigation和BottomNavigationView的使用,可以实现底部导航栏。
如果你的viewpager+tab是非滚动不左右滑动切换页面,可以更换了。
新建activity,选择Bottom Navigation Activity:
Bottom Navigation activity
如果新建activity没有该选项的话,请升级Android studio
代码自动产生activity,xml,menu,drawable。创建4个fragment,此处代码忽略,然后创建navigation,如何创建参考使用一
nav_bottom_navagation.xml代码如下:
<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"
app:startDestination="@id/nav_home"
android:id="@+id/nav_bottom_navagation">
<fragment
android:id="@+id/nav_home"
android:name="com.ghp.demo.databindingdemoproject.navigation.bottomNavigationView.HomeFragment"
android:label="@string/title_home"
tools:layout="@layout/fragment_home">
</fragment>
<fragment
android:id="@+id/nav_dashboard"
android:name="com.ghp.demo.databindingdemoproject.navigation.bottomNavigationView.DashboardFragment"
android:label="@string/title_dashboard"
tools:layout="@layout/fragment_dashboard">
</fragment>
<fragment
android:id="@+id/nav_notifications"
android:name="com.ghp.demo.databindingdemoproject.navigation.bottomNavigationView.NotificationsFragment"
android:label="@string/title_notifications"
tools:layout="@layout/fragment_notifications">
</fragment>
</navigation>
接着我们修改activity的XML,将自动产生的TextView替换为fragment
<layout 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.support.constraint.ConstraintLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".navigation.bottomNavigationView.BottomNavigationActivity">
<fragment
android:id="@+id/frag_nav_bottom_navigation"
android:layout_width="0dp"
android:layout_height="0dp"
android:name="androidx.navigation.fragment.NavHostFragment"
app:defaultNavHost="true"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toTopOf="@id/navigation"
app:navGraph="@navigation/nav_bottom_navagation"
/>
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/bottom_navigation" />
</android.support.constraint