Same Navigation Drawer in different Activities

Multi tool use
Multi tool use


Same Navigation Drawer in different Activities



I made a working navigation drawer like it's shown in the tutorial on the developer.android.com website. But now, I want to use one Navigation Drawer, i created in the NavigationDrawer.class for multiple Activities in my Application.



My question is, if anyone here can make a little Tutorial, which explains, how to use one Navigation drawer for multiple Activities.



I read it first at this Answer
Android Navigation Drawer on multiple Activities



but it didn't work on my Project


public class NavigationDrawer extends Activity {
public DrawerLayout drawerLayout;
public ListView drawerList;
private ActionBarDrawerToggle drawerToggle;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle((Activity) this, drawerLayout, R.drawable.ic_drawer, 0, 0) {

public void onDrawerClosed(View view) {
getActionBar().setTitle(R.string.app_name);
}

public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.menu);
}
};
drawerLayout.setDrawerListener(drawerToggle);

getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);

layers = getResources().getStringArray(R.array.layers_array);
drawerList = (ListView) findViewById(R.id.left_drawer);
View header = getLayoutInflater().inflate(R.layout.drawer_list_header, null);
drawerList.addHeaderView(header, null, false);
drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, android.R.id.text1,
layers));
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.drawer_list_footer, null, false);
drawerList.addFooterView(footerView);

drawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
map.drawerClickEvent(pos);
}
});
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);

}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}



In this Activity i want to have the Navigation Drawer so I extends 'NavigationDrawer' and in some other Activities i want to User the Same Navigation drawer


public class SampleActivity extends NavigationDrawer {...}



I don't know what to change...





You can find the examples here.
– Naddy
Jul 7 '14 at 3:24





you can find from : stackoverflow.com/questions/33009469/…
– varotariya vajsi
Mar 1 '17 at 14:19




11 Answers
11



If you want a navigation drawer, you should use fragments.
I followed this tutorial last week and it works great:



http://developer.android.com/training/implementing-navigation/nav-drawer.html



You can also download sample code from this tutorial, to see how you can do this.



Without fragments:



This is your BaseActivity Code:


public class BaseActivity extends Activity
{
public DrawerLayout drawerLayout;
public ListView drawerList;
public String layers;
private ActionBarDrawerToggle drawerToggle;
private Map map;

protected void onCreate(Bundle savedInstanceState)
{
// R.id.drawer_layout should be in every activity with exactly the same id.
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

drawerToggle = new ActionBarDrawerToggle((Activity) this, drawerLayout, R.drawable.ic_drawer, 0, 0)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(R.string.app_name);
}

public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(R.string.menu);
}
};
drawerLayout.setDrawerListener(drawerToggle);

getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);

layers = getResources().getStringArray(R.array.layers_array);
drawerList = (ListView) findViewById(R.id.left_drawer);
View header = getLayoutInflater().inflate(R.layout.drawer_list_header, null);
drawerList.addHeaderView(header, null, false);
drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, android.R.id.text1,
layers));
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.drawer_list_footer, null, false);
drawerList.addFooterView(footerView);

drawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
map.drawerClickEvent(pos);
}
});
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);

}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}



All the other Activities that needs to have a navigation drawer should extend this Activity instead of Activity itself, example:


public class AnyActivity extends BaseActivity
{
//Because this activity extends BaseActivity it automatically has the navigation drawer
//You can just write your normal Activity code and you don't need to add anything for the navigation drawer
}



XML


<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Put what you want as your normal screen in here, you can also choose for a linear layout or any other layout, whatever you prefer -->
</FrameLayout>
<!-- The navigation drawer -->
<ListView android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>



Edit:



I experienced some difficulties myself, so here is a solution if you get NullPointerExceptions. In BaseActivity change the onCreate function to protected void onCreateDrawer(). The rest can stay the same. In the Activities which extend BaseActivity put the code in this order:


protected void onCreateDrawer()


super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
super.onCreateDrawer();



This helped me fix my problem, hope it helps!



This is how you can create a navigation drawer with multiple activities, if you have any questions feel free to ask.



Edit 2:



As said by @GregDan your BaseActivity can also override setContentView() and call onCreateDrawer there:


BaseActivity


setContentView()


@Override
public void setContentView(@LayoutRes int layoutResID)
{
super.setContentView(layoutResID);
onCreateDrawer() ;
}





I don't want to use activitys over fragments, I just want to use different activitys which uses all the same navigation drawer. I want activity, because there I can use different types of layout like swipe view, map view...
– MEX
Oct 21 '13 at 13:24





Having just one Activity can be a daunting task for any fairly complex app. Using Activities gives you a lot of free things from the system - so it is a valid point how to use multiple Activities. I can't imagine one Activity handling communication between any number of fragment combinations - it's just not gonna work.
– slott
Nov 7 '13 at 9:39





I'm sorry it took so long for me to answer. I Edited my answer. I believe this is the tutorial you were looking for. Hope this helps.
– Kevin van Mierlo
Dec 2 '13 at 11:07





@KevinvanMierlo can you tell me what you mean by: R.id.drawer_layout should be in every activity with exactly the same id. Because I did exactly what you told here and I get a NullPointerException in onCreate() method of the Activity that extends this BaseActivity..
– Loolooii
Feb 19 '14 at 22:17





@KevinvanMierlo btw, I think you forgot these 2 lines? super.onCreate(savedInstanceState); setContentView(R.layout.activity_base);
– Loolooii
Feb 21 '14 at 20:09



I've found the best implementation. It's in the Google I/O 2014 app.



They use the same approach as Kevin's. If you can abstract yourself from all unneeded stuff in I/O app, you could extract everything you need and it is assured by Google that it's a correct usage of navigation drawer pattern.
Each activity optionally has a DrawerLayout as its main layout. The interesting part is how the navigation to other screens is done. It is implemented in BaseActivity like this:


DrawerLayout


BaseActivity


private void goToNavDrawerItem(int item) {
Intent intent;
switch (item) {
case NAVDRAWER_ITEM_MY_SCHEDULE:
intent = new Intent(this, MyScheduleActivity.class);
startActivity(intent);
finish();
break;



This differs from the common way of replacing current fragment by a fragment transaction. But the user doesn't spot a visual difference.





This ^ I cant figure out how they start new activities and it works flawlessly. It's a large app to work through.
– hitch.united
Feb 16 '15 at 19:48





@hitch.united That's because they use a lot of fragments and just a few activities.
– Joaquin Iurchuk
May 5 '15 at 12:00





@hitch.united they probably override the animation of the activity with overridePendingTransitions.
– EpicPandaForce
May 14 '15 at 13:39


overridePendingTransitions





is Loading fragments instead of subclassing activities?
– Vikas Pandey
Jul 20 '17 at 7:23





Here's the file from October 2014: github.com/google/iosched/blob/…
– rafid059
Dec 28 '17 at 11:35



For anyone else looking to do what the original poster is asking, please consider to use fragments instead the way Kevin said. Here is an excellent tutorial on how to do that:



https://github.com/codepath/android_guides/wiki/Fragment-Navigation-Drawer



If you choose to instead use activities instead of fragments you are going to run into the problem of the nav drawer being re-created every time you navigate to a new activity. This results in an ugly/slow rendering of the nav drawer each time.



So this answer is a few years late but someone may appreciate it. Android has given us a new widget that makes using one navigation drawer with several activities easier.



android.support.design.widget.NavigationView is modular and has its own layout in the menu folder. The way that you use it is to wrap xml layouts the following way:



Root Layout is a android.support.v4.widget.DrawerLayout that contains two children: an <include ... /> for the layout that is being wrapped (see 2) and a android.support.design.widget.NavigationView.


<include ... />


<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />





nav_header_main is just a LinearLayout with orientation = vertical for the header of your Navigation Drawar.



activity_main_drawer is a menu xml in your res/menu directory. It can contain items and groups of your choice. If you use the AndroidStudio Gallery the wizard will make a basic one for you and you can see what your options are.



App bar layout is usually now a android.support.design.widget.CoordinatorLayout and this will include two children: a android.support.design.widget.AppBarLayout (which contains a android.support.v7.widget.Toolbar) and an <include ... > for your actual content (see 3).


<include ... >


<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="yourpackage.MainActivity">

<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />





Content layout can be whatever layout you want. This is the layout that contains the main content of the activity (not including the navigation drawer or app bar).



Now, the cool thing about all of this is that you can wrap each activity in these two layouts but have your NavigationView (see step 1) always point to activity_main_drawer (or whatever). This means that you will have the same(*) Navigation Drawer on all activities.





stackoverflow is cutting off some of the enclosing xml brackets but the important stuff is all there.
– jwehrle
Oct 6 '17 at 22:34



Easiest way to reuse a common Navigation drawer among a group of activities



app_base_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">

<FrameLayout
android:id="@+id/view_stub"
android:layout_width="match_parent"
android:layout_height="match_parent">

</FrameLayout>

<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/menu_test"
/>
</android.support.v4.widget.DrawerLayout>



AppBaseActivity.java


/*
* This is a simple and easy approach to reuse the same
* navigation drawer on your other activities. Just create
* a base layout that conains a DrawerLayout, the
* navigation drawer and a FrameLayout to hold your
* content view. All you have to do is to extend your
* activities from this class to set that navigation
* drawer. Happy hacking :)
* P.S: You don't need to declare this Activity in the
* AndroidManifest.xml. This is just a base class.
*/
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

public abstract class AppBaseActivity extends AppCompatActivity implements MenuItem.OnMenuItemClickListener {
private FrameLayout view_stub; //This is the framelayout to keep your content view
private NavigationView navigation_view; // The new navigation view from Android Design Library. Can inflate menu resources. Easy
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private Menu drawerMenu;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.app_base_layout);// The base layout that contains your navigation drawer.
view_stub = (FrameLayout) findViewById(R.id.view_stub);
navigation_view = (NavigationView) findViewById(R.id.navigation_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, 0, 0);
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

drawerMenu = navigation_view.getMenu();
for(int i = 0; i < drawerMenu.size(); i++) {
drawerMenu.getItem(i).setOnMenuItemClickListener(this);
}
// and so on...
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}

/* Override all setContentView methods to put the content view to the FrameLayout view_stub
* so that, we can make other activity implementations looks like normal activity subclasses.
*/
@Override
public void setContentView(int layoutResID) {
if (view_stub != null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
View stubView = inflater.inflate(layoutResID, view_stub, false);
view_stub.addView(stubView, lp);
}
}

@Override
public void setContentView(View view) {
if (view_stub != null) {
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
view_stub.addView(view, lp);
}
}

@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
if (view_stub != null) {
view_stub.addView(view, params);
}
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...

return super.onOptionsItemSelected(item);
}

@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
// handle it
break;
case R.id.item2:
// do whatever
break;
// and so on...
}
return false;
}
}



There is a work around: In my implementation: I have fragments in first activity that has Navigation Drawer. The other activities create the ActionBar and Navigation Drawer from the same code as first activity, and they do not have fragments, the laying out is described later here. In the first activity, the action click of the item is handled in the same activity, and in the other activities, the action is completed later, first I switch to the first activity, by closing the other activities. The conditions are as follows:



I have put the main layout and inside first framelayout, and second framelayout is dedicated to the Drawer in DrawerLayout.



I have done the drawer initialization in onResume of the activities other than the first one. This is because it needs to re-initialize after on new intent updates, as all the activities are single instance.



This way I have been able to have NavigationDrawer and ActionBarCompat in all the activities.



The other way around could be: do not use activities at all, instead use fragments, and replace them in the container (Linear Layout for example) where you show your first fragment.



Code is available in Android Developer Tutorials, you just have to customize.



http://developer.android.com/training/implementing-navigation/nav-drawer.html



It is advisable that you should use more and more fragments in your application, and there should be only three activities local to your application, that you mention in your AndroidManifest.xml apart from the external ones (FacebookActivity for example):



SplashActivity: uses no fragment, and uses FullScreen theme.



LoginSignUpActivity: Do not require NavigationDrawer at all, so simply use normal tool bar, but at the least, 3 or 4 fragments will be required. Uses noactionbar theme



HomeActivity or DashBoardActivity: Uses noactionbar theme. Here you require Navigation drawer, also all the screens that follow will be fragments or nested fragments, till the leaf view. All the settings, user profile and etc. will be here as fragments, in this activity.



Happy Coding !!





Please, consider add an example and some code...
– Cabuxa.Mapache
Jun 13 '16 at 14:22





This is an older post. You can use fragments to ensure you have one activity always. You keep replacing the fragments in one container dedicated to it. Put in back stack when you need backward navigation, or pop all the fragments when you need a fragment to be shown as the first one.
– Abhinav Saxena
Jun 15 '16 at 9:49



update this code in baseactivity. and dont forget to include drawer_list_header in your activity xml.


super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.drawer_list_header);



and dont use request() in your activity. but still the drawer is not visible on clicking image..and by dragging it will visible without list items. i tried a lot but no success. need some workouts for this...



With @Kevin van Mierlo 's answer, you are also capable of implementing several drawers. For instance, the default menu located on the left side (start), and a further optional menu, located on the right side, which is only shown when determinate fragments are loaded.



I've been able to do that.


package xxxxxx;



import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.widget.SearchView;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;


public class loginhome extends AppCompatActivity {
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;

// Make sure to be using android.support.v7.app.ActionBarDrawerToggle version.
// The android.support.v4.app.ActionBarDrawerToggle has been deprecated.
private ActionBarDrawerToggle drawerToggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginhome);

// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);


//Initializing NavigationView


navigationView = (NavigationView) findViewById(R.id.nav_view);

//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

// This method will trigger on item Click of navigation menu

public boolean onNavigationItemSelected(MenuItem menuItem) {


//Checking if the item is in checked state or not, if not make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);

//Closing drawer on item click
drawerLayout.closeDrawers();

//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()){


//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.nav_first_fragment:
Toast.makeText(getApplicationContext(),"First fragment",Toast.LENGTH_SHORT).show();
FirstFragment fragment = new FirstFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
return true;

// For rest of the options we just show a toast on click
case R.id.nav_second_fragment:
Toast.makeText(getApplicationContext(),"Second fragment",Toast.LENGTH_SHORT).show();
SecondFragment fragment2 = new SecondFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction2 = getSupportFragmentManager().beginTransaction();
fragmentTransaction2.replace(R.id.frame,fragment2);
fragmentTransaction2.commit();
return true;

default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
return true;

}
}
});

// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open, R.string.drawer_close){

@Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}

@Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

super.onDrawerOpened(drawerView);
}
};

//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);

//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();







}



use this for your toolbar.xml


<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:elevation="4dp"
android:id="@+id/toolbar"
android:theme="@style/ThemeOverlay.AppCompat.Dark"


>

</android.support.v7.widget.Toolbar>



use this for navigation header if want to use


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="192dp"
android:background="?attr/colorPrimaryDark"
android:padding="16dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
android:orientation="vertical"
android:gravity="bottom">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:id="@+id/navhead"
android:orientation="vertical"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">

<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:textColor="#ffffff"
android:text="tanya"
android:textSize="14sp"
android:textStyle="bold"

/>

<TextView
android:id="@+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:layout_marginLeft="16dp"
android:layout_marginTop="5dp"
android:text="tanya.com"
android:textSize="14sp"
android:textStyle="normal"

/>
</LinearLayout>
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_below="@+id/imageView"
android:layout_marginTop="15dp"

android:src="@drawable/face"
android:id="@+id/circleView"
/>



</RelativeLayout>



I do it in Kotlin like this:


open class BaseAppCompatActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

protected lateinit var drawerLayout: DrawerLayout
protected lateinit var navigationView: NavigationView
@Inject
lateinit var loginService: LoginService

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d("BaseAppCompatActivity", "onCreate()")
App.getComponent().inject(this)
drawerLayout = findViewById(R.id.drawer_layout) as DrawerLayout

val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)

navigationView = findViewById(R.id.nav_view) as NavigationView
navigationView.setNavigationItemSelectedListener(this)

val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)

drawerLayout.addDrawerListener(toggle)
toggle.syncState()
toggle.isDrawerIndicatorEnabled = true

val navigationViewHeaderView = navigationView.getHeaderView(0)
navigationViewHeaderView.login_txt.text = SharedKey.username
}
private inline fun <reified T: Activity> launch():Boolean{
if(this is T) return closeDrawer()
val intent = Intent(applicationContext, T::class.java)
startActivity(intent)
finish()
return true
}

private fun closeDrawer(): Boolean {
drawerLayout.closeDrawer(GravityCompat.START)
return true
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
val id = item.itemId

when (id) {
R.id.action_tasks -> {
return launch<TasksActivity>()
}
R.id.action_contacts -> {
return launch<ContactActivity>()
}
R.id.action_logout -> {
createExitDialog(loginService, this)
}
}
return false
}
}



Activities for drawer must inherit this BaseAppCompatActivity, call super.onCreate after content is set (actually, can be moved to some init method) and have corresponding elements for ids in their layout


BaseAppCompatActivity


super.onCreate





I wanted to try your solution but I get this error: "This Activity already has an action bar supplied by the window decor". I want to switch between 3 activities and each other has its own app bar. Do you think that is possible ?
– davoid
Jan 19 at 12:00






I think, you need to move your actionbar to fragments in that case. In our app we used NoActionBar theme and provided toolbar for compatibility, as far as i remember.
– Pavlus
Jan 20 at 13:35



Create Navigation drawer in your MainActivity using fragment.
Initialize the Navigation Drawer in MainActivity
now in all other activities you want to use same Navigation Drawer put DrawerLayout as base and fragment as navigation drawer. Just set android:name in your fragment pointing to your fragment Java file. You won't need to initialize the fragment in other Activities.
You can access Nav Drawer by swipe in other activities like in Google Play Store app




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).


Would you like to answer one of these unanswered questions instead?

stwBMfPjs n AvmawCrWq
1yu hqWJKUBAv

Popular posts from this blog

Delphi Android file open failure with API 26

.

Amasya