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
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