Switch between Fragments with onNavigationItemSelected in new Navigation Drawer Activity template (Android Studio 1.4 onward)

前端 未结 6 2034
旧时难觅i
旧时难觅i 2020-11-30 19:31

IntelliJ has made changes to the Navigation Drawer template Activity in Android Studio with fewer lines of code in the Activity class. The new Activity class looks like this

6条回答
  •  一整个雨季
    2020-11-30 19:45

    You should not change the DrawerLayout, you only need to add a frame in the "content_main.xml".

    Follow the steps below:

    1. open the "content_main.xml" file located in the "layout" folder.

    2. use the code below:

       
          
          
             
      
      
    3. go to the onNavigationItemSelected method:

      public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        Fragment fragment;
      
      if (id == R.id.nav_camara) {
          fragment = new YourFragment();
          FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
          ft.replace(R.id.mainFrame, fragment);
          ft.commit();
      }
      else if (id == R.id.nav_gallery) {
      
      }
      else if (id == R.id.nav_slideshow) {
      
      }
      else if (id == R.id.nav_manage) {
      
      } else if (id == R.id.nav_share) {
      
      } else if (id == R.id.nav_send) {
      
      }
      
      DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
      drawer.closeDrawer(GravityCompat.START);
      return true;
      }
      

提交回复
热议问题