<androidx.fragment.app.FragmentContainerView
android:id="@+id/fcv_content"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0px"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@id/bnv_menu"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/cl_title"
app:navGraph="@navigation/nav_main" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bnv_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/black"
android:elevation="1dp"
app:itemIconTint="@drawable/bottom_btn_selected_color"
app:labelVisibilityMode="labeled"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="@menu/bottom_menu" />
添加menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/homeFragment"
android:icon="@mipmap/icon_home"
android:iconTint="@color/white"
android:title="首页" />
<item
android:id="@+id/setFragment"
android:iconTint="@color/white"
android:icon="@mipmap/icon_set"
android:title="设置" />
</menu>
添加navigation
<?xml version="1.0" encoding="utf-8"?>
<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_main"
app:startDestination="@id/homeFragment">
<fragment
android:id="@+id/homeFragment"
android:name="com.example.demo.ui.fragment.HomeFragment"
tools:layout="@layout/fragment_home"
android:label="HomeFragment" />
<fragment
android:id="@+id/setFragment"
android:name="com.example.demo.ui.fragment.SetFragment"
tools:layout="@layout/fragment_set"
android:label="SetFragment" />
</navigation>
MainActivity代码
public class MainActivity extends AppCompatActivity {
BottomNavigationView bnv_menu;
NavHostFragment fcv_content;
NavController navController = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
bnv_menu = findViewById(R.id.bnv_menu);
/***
*下面是主要代码
*实现BottomNavigationView和Navigation联动
***/
fcv_content = (NavHostFragment) getSupportFragmentManager()
.findFragmentById(R.id.fcv_content);
if (fcv_content != null) {
navController = fcv_content.getNavController();
}
NavigationUI.setupWithNavController(bnv_menu, navController);
}
}
需要注意