You can better use a non-active fragment to add content for each navigation option (after creating the application using the Activity Navigation Drawer function in Android Studio).
content_main.xml (assign id to this relative location, Example: android: id = "@ + id / relative_layout_for_fragment")
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.example.root.netutility.MainActivity" tools:showIn="@layout/app_bar_main" android:id="@+id/relative_layout_for_fragment"> </RelativeLayout>
MainActivity.Java (You are changing snippets like this)
@Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); Fragment fragment = null; if (id == R.id.ping_tab) { fragment = new FirstFragment(); toolbar.setTitle("First"); } else if (id == R.id.traceroute_tab) { fragment = new SecondFragment(); toolbar.setTitle("Second"); // if you wan to change title }else if (id == R.id.nav_share) { fragment = new ThirdFragment(); } else if (id == R.id.nav_send) { fragment = new FourthFragment(); } if(fragment != null) { // update the main content by replacing fragments FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.relative_layout_for_fragment, fragment).commit(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; }
Shivbuyya
source share