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

前端 未结 6 2037
旧时难觅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 20:02

    I used a template auto-created by Android Studio 1.4 too, and I had encounter same difficulties as you.

    First, I changed activity_main.xml

    
    
    
    
    
        
        
        
        
    
    
    
    
    

    A DrawerLayout that contains two parts:

    1. Main Screen (LinearLayout)
    2. the Drawer (NavigationView)

    Main Screen contains the ActionBar and the FrameLayout (R.id.content) will be replaced by a fragment. The Drawer contains the header and the menu.

    So, we now override onNavigationItemSelected and replace R.id.content with a fragment.

    Here is my MainActivity code:

        @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        Fragment fragment;
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        // Handle navigation view item clicks here.
        int id = item.getItemId();
    
        if (id == R.id.nav_A) {
            fragment = new AFragment();
            ft.replace(R.id.content, fragment).commit();        
        } else if (id == R.id.nav_B){
            fragment = new BFragment();
            ft.replace(R.id.content, fragment).commit();
        } else if (id == R.id.nav_settings) {
            Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
            startActivity(intent);
        }
    
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    

    Main page is also a fragment. And I set up main page in onCreate method although I am not sure if there is a better way to set up main page.

    //MainPageFragment
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.content, new MainPageFragment()).commit();
    

    PS. here is the toolbar.xml, the ActionBar

    
    
    
        
    
    
    

提交回复
热议问题