Android: Navigation-Drawer en todas las actividades

Quiero agregar un cajón de navegación en todas las actividades de mi proyecto de Android. Este es el código de la actividad principal:

public class MainActivity extends Activity { private String[] drawerListViewItems; private DrawerLayout drawerLayout; private ListView drawerListView; private ActionBarDrawerToggle actionBarDrawerToggle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // get list items from strings.xml drawerListViewItems = getResources().getStringArray(R.array.items); // get ListView defined in activity_main.xml drawerListView = (ListView) findViewById(R.id.left_drawer); // Set the adapter for the list view drawerListView.setAdapter(new ArrayAdapter(this, R.layout.drawer_listview_item, drawerListViewItems)); // App Icon drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); //drawerLayout = (DrawerLayout) findViewById(R.drawable.ic_drawer_2); actionBarDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ drawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ ); // Set actionBarDrawerToggle as the DrawerListener drawerLayout.setDrawerListener(actionBarDrawerToggle); getActionBar().setDisplayHomeAsUpEnabled(true); // just styling option add shadow the right edge of the drawer drawerLayout.setDrawerShadow(R.drawable.ic_drawer, GravityCompat.START); drawerListView.setOnItemClickListener(new DrawerItemClickListener()); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. actionBarDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); actionBarDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { // call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true // then it has handled the app icon touch event if (actionBarDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { displayView(position); drawerLayout.closeDrawer(drawerListView); } private void displayView(int position) { switch (position) { case 0: secondactivity(); break; case 1: Toast.makeText(MainActivity.this, "2", Toast.LENGTH_LONG).show(); break; case 2: Toast.makeText(MainActivity.this, "3", Toast.LENGTH_LONG).show(); default: break; } } } public void secondactivity (){ Intent cambioActivity; cambioActivity = new Intent (this, SecondActivity.class); startActivity(cambioActivity); } } 

En este código creo el cajón de navegación, quiero el cajón de navegación en todas las actividades, por lo que el código de mi Segunda Actividad es este:

 public class SecondActivity extends MainActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_secondactivity); } 

El panel de navegación está en la primera actividad pero no hay otras actividades, ¿por qué? ¿Alguien me puede ayudar?

La manera fácil es que debes crear fragmentos. Si estás listo para algo poco difícil, entonces esto es para ti. Le permitirá tener el mismo panel de navegación en todas las actividades.

Crear drawer_n_activity.xml

      

Your DrawerActivity.class

 public class DrawerActivity extends Activity { public RelativeLayout fullLayout; public FrameLayout frameLayout; @Override public void setContentView(int layoutResID) { fullLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.drawer_n_activity, null); frameLayout = (FrameLayout) fullLayout.findViewById(R.id.drawer_frame); getLayoutInflater().inflate(layoutResID, frameLayout, true); super.setContentView(fullLayout); //Your drawer content... } } 

Ahora, para incluir el mismo Cajón de navegación en todas sus actividades y tener en mente una cosa más, todas sus actividades deben extenderse. DrawerActivity

 public class MainActivity extends DrawerActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //layout for 1st activity } } public class SecondActivity extends DrawerActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_activity); //layout for 2nd activity } } 

De acuerdo, los chicos compartirán mi forma de hacerlo (en caso de que estés desarrollando un proyecto después de alguien y ya hay toneladas de actividades).

Finalmente infló el cajón de navegación con una línea de código (en onCreate ):

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = this; //context //setContentView(R.layout.activity_favorites); // Was so Utils.inflatedNavigationDrawerView(mContext, R.layout.activity_favorites); // Now is //... } 

siguiente, ¿qué es Utils ? :

 public class Utils{ public static void inflatedNavigationDrawerView(Context context, int layoutId){ // Here get view of clear DrawerLayout final View drawerLayout = View.inflate(context,R.layout.navigation_drawer_inflator, null); // Next inflate to it passed layout for activity final View mainLayout = View.inflate(context,layoutId, (ViewGroup) drawerLayout); // And finally inflate to it fragment for NavigationDraver final View fragmentLayout = View.inflate(context,R.layout.navigation_drawer_inflator_fragment, (ViewGroup) drawerLayout); // Next we should try to get our drawer (should check with casting to each activity you want to insert to) NavigationDrawerFragment drawerFragment = null; // this block should be repeated for each activity you want to use in. if (context instanceof FavoritesActivity){ // Set our pack of inflates to contentview ((FavoritesActivity) context).setContentView(mainLayout); // And now we get NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) ((FavoritesActivity) context).getSupportFragmentManager().findFragmentById(R.id.navigation_drawer_fragment); } if(drawerFragment != null){ // if null then we missed some castings for activity used in. // Finally setup our drawer drawerFragment.setUpEasy(R.id.navigation_drawer_fragment, (DrawerLayout)drawerLayout.findViewById(R.id.drawer_layout), (Toolbar) mainLayout.findViewById(R.id.app_bar)); } } } 

Si desea evitar la creación de hamburguesas en la barra de herramientas, debe configurar el lugar mDrawerToggle.setDrawerIndicatorEnabled(false); : mDrawerToggle.setDrawerIndicatorEnabled(false);

Aquí está mi muestra de configuración:

 public void setUpEasy(int fragmentId, DrawerLayout drawerLayout, Toolbar toolBar) { mContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolBar, R.string.open, R.string.close){ @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if(!mUserLearnedDrawer){ mUserLearnedDrawer = true; saveToPreferences(getActivity(), Constants.PREFERENCES_LEARNDRAWER_KEY, mUserLearnedDrawer+""); } } @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); } }; mDrawerToggle.setDrawerIndicatorEnabled(false); // If false then no hamburger menu. mDrawerLayout.setDrawerListener(mDrawerToggle); mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); } 

y vistas usadas:

// navigation_drawer_inflator.xml

    

// navigation_drawer_inflator_fragment.xml

   

Finalmente, si implementa esto: podrá insertar el panel de navegación en cualquier actividad en ejecución. Saludos 🙂

Así es como lo hice. Crea la clase de ayuda. También agregué un código opcional para la capacidad de terminar () la clase.

 public class NavDrawerHelper extends ContextWrapper{ public NavDrawerHelper(Context context){ super(context); } public void initNav(final DrawerLayout drawerLayout, NavigationView navigationView, Toolbar toolbar, final boolean isFinish){ navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { int id = menuItem.getItemId(); switch (id){ case R.id.nav_home: startActivity(new Intent(getBaseContext(), MainActivity.class)); if (isFinish) ((Activity)getBaseContext()).finish(); drawerLayout.closeDrawers(); break; case R.id.nav_settings: startActivity(new Intent(getBaseContext(), SettingsActivity.class)); if (isFinish) ((Activity)getBaseContext()).finish(); drawerLayout.closeDrawers(); break; } return true; } }); ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(((Activity)getBaseContext()),drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){ @Override public void onDrawerClosed(View v){ super.onDrawerClosed(v); } @Override public void onDrawerOpened(View v) { super.onDrawerOpened(v); } }; drawerLayout.addDrawerListener(actionBarDrawerToggle); actionBarDrawerToggle.syncState(); } 

}

luego agrega este código a todas las actividades. Esto reemplaza su método initNavigationDrawer () existente.

  public void initNavigationDrawer() { //views NavigationView navigationView = findViewById(R.id.navigation_view); DrawerLayout drawerLayout = findViewById(R.id.drawer); NavDrawerHelper navDrawerHelper = new NavDrawerHelper(this); navDrawerHelper.initNav(drawerLayout, navigationView, toolbar, false); 

}