Android - Navigation drawer fragments

后端 未结 3 1618
粉色の甜心
粉色の甜心 2021-01-06 12:24

I have implemented navigation drawer in my android app. but now I want to be able to change the layout using fragments when the user clicks any list item in the navigation b

3条回答
  •  臣服心动
    2021-01-06 12:31

    After generate a Navigation Drawer Activity by File->New->Activity->Navigation Drawer Activity, here are 3 steps

    First, go to app_bar_main.xml then

    replace

    by

    
    

    Second, go to MainActivity -> onNavigationItemSelected then modify it like

    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        Fragment fragment = null;
        if (id == R.id.nav_camera) {
            fragment = CameraFragment.newInstance();
        } else if (id == R.id.nav_gallery) {
            fragment = GalleryFragment.newInstance();
        } else if (id == R.id.nav_slideshow) {
            fragment = SlideShowFragment.newInstance();
        }
    
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame_content, fragment).commit();
    
        setTitle(item.getTitle());
    
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    

    Finally, create Fragment class, example a Fragment

    public class CameraFragment extends Fragment{
    
        public static CameraFragment newInstance() {
             Bundle args = new Bundle();
             CameraFragment fragment = new CameraFragment();
            fragment.setArguments(args);
            return fragment;
        }
    
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                @Nullable Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_camera, null, false);
            return rootView;
        }
    }
    

    Demo project

提交回复
热议问题