Если вы используете androidX, вы должны использовать NavController для навигации по фрагментам.
Я опубликую код, который я пробовал
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
NavController mNavController;
Navigation mNavigation;
BottomNavigationView mBottomNavigationView;
NavigationView mNavigationView;
DrawerLayout mDrawerLayout;
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mDrawerLayout = findViewById(R.id.drawer_layout);
mBottomNavigationView = findViewById(R.id.bottom_navigation_view);
mNavigationView = findViewById(R.id.navigation_view);
//mNavController = Navigation.findNavController(this,R.id.host_fragment);
mNavController = Navigation.findNavController(this,R.id.host_fragment);
NavigationUI.setupWithNavController(mBottomNavigationView,Navigation.findNavController(this,R.id.host_fragment));
NavigationUI.setupActionBarWithNavController(this, mNavController, mDrawerLayout);
NavigationUI.setupWithNavController(mNavigationView,mNavController);
mNavigationView.setNavigationItemSelectedListener(this);
//NavigationUI.setupActionBarWithNavController(this,Navigation.findNavController(this,R.id.host_fragment));
}
@Override
public boolean onSupportNavigateUp() {
/*return mNavController.popBackStack(R.id.host_fragment,false);*/
return NavigationUI.navigateUp(Navigation.findNavController(this, R.id.host_fragment), mDrawerLayout);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onBackPressed() {
NavController navController = Navigation.findNavController(this, R.id.host_fragment);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (Objects.requireNonNull(navController.getCurrentDestination()).getId() == R.id.nav_first) {
finishAffinity();
} else {
mNavController.popBackStack(R.id.nav_first, false);
}
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.home:
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
mDrawerLayout.closeDrawers();
int id = menuItem.getItemId();
switch (id){
//Nav drawer items
case R.id.profile:
mNavController.navigate(R.id.profile);
break;
case R.id.features:
mNavController.navigate(R.id.features);
break;
case R.id.signOut:
finishAffinity();
break;
}
return true;
}
}
Вы должны иметь фрагмент хоста, где вам нужно внедрить фрагменты в макете активности, где вы реализуете Navigation
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:background="@android:color/white"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="10">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/toolbar_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="8"
android:gravity="center"
android:padding="10dp"
android:text="@string/jetpack_example"
android:textColor="#000"
android:textSize="15sp" />
<ImageView
android:id="@+id/search_bar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="2"
android:padding="10dp"
android:src="@drawable/about_icon" />
</LinearLayout>
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemBackground="@android:color/white"
app:labelVisibilityMode="selected"
app:layout_constraintBottom_toBottomOf="@+id/host_fragment"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="@menu/menu_drawer" />
<fragment
android:id="@+id/host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/navigation_graph"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/navigation_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/nav_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
Далее вам нужен график навигации дляНавигация и использование аргументов. Вы также можете реализовать действия. Создайте папку навигации и внедрите приведенный ниже фрагмент, реализующий фрагмент, когда вы щелкнете по конкретному элементу.
navigation_graph.xml
<?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/navigation_graph"
app:startDestination="@id/nav_first">
<fragment
android:id="@+id/nav_first"
android:name="com.escapadetechnologies.jetpacknavigationexample.Fragments.FirstFragment"
android:label="@string/first"
tools:layout="@layout/fragment_first" />
<fragment
android:id="@+id/nav_second"
android:name="com.escapadetechnologies.jetpacknavigationexample.Fragments.SecondFragment"
android:label="@string/second"
tools:layout="@layout/fragment_second" />
<fragment
android:id="@+id/nav_third"
android:name="com.escapadetechnologies.jetpacknavigationexample.Fragments.ThirdFragment"
android:label="@string/third"
tools:layout="@layout/fragment_third" />
<fragment
android:id="@+id/nav_fourth"
android:name="com.escapadetechnologies.jetpacknavigationexample.Fragments.FourthFragment"
android:label="@string/fourth"
tools:layout="@layout/fragment_fourth" />
<fragment
android:id="@+id/profile"
android:name="com.escapadetechnologies.jetpacknavigationexample.Fragments.ProfileFragment"
android:label="@string/profile"
tools:layout="@layout/fragment_profile" />
<fragment
android:id="@+id/features"
android:name="com.escapadetechnologies.jetpacknavigationexample.Fragments.FeaturesFragment"
android:label="@string/features"
tools:layout="@layout/fragment_features" />
Это очень удобно, и с помощью androidx можно избежать большого количества стандартного кода. Если у вас есть какие-либо сомнения, вы можете прокомментировать мой ответ.