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

前端 未结 6 2035
旧时难觅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:43

    another way is:

    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        Fragment fragment;
        int id = item.getItemId();
    
        if (id == R.id.nav_camera) {
            // Handle the camera action
            fragment = new BlankFragment();
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.container_new, fragment);
            ft.commit();
        } else if (id == R.id.nav_gallery) {
            fragment = new HorizontalView();
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.container_new,fragment);
            ft.commit();
        } else if (id == R.id.nav_slideshow) {
            fragment = new FragmentVerticleView();
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.container_new,fragment);
            ft.commit();
    
        } 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;
    }
    

    And then you'll need to implemts all the fragments to your activity. In my case it's

    MainActivity.java

        public class MainActivity extends AppCompatActivity
        implements BlankFragment.OnFragmentInteractionListener, HorizontalView.OnFragmentInteractionListener,FragmentVerticleView.OnFragmentInteractionListener,OnNavigationItemSelectedListener
         { 
        //coding stuff
        }
    

    And to handle the Exception that is Thrown in fragment java file

        "must implement OnFragmentInteractionListener"
    

    you simply add below method

          public void    onFragmentInteraction(Uri uri){
        //We can keep this empty
    }
    

    And there you go! All set

    Thanks to this Tutorial to strike this

提交回复
热议问题