Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Display Navigation Drawer in all activities?

I have a Navigation Drawer which should appear in all my activities.

I saw many questions similar to this & found a solution like Extending the MainActivity with the Other Activities .

So i extended My Main Activity to my Second Activity.But the Drawer is not being showed in the Second Activity

MainActivity

public class MainActivity extends ActionBarActivity
{
    private ListView mDrawerList;
    private DrawerLayout mDrawer;
    private CustomActionBarDrawerToggle mDrawerToggle;
    private String[] menuItems;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_BAR);
    // getSupportActionBar().hide();
    setContentView(R.layout.activity_main_drawer);

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    // set a custom shadow that overlays the main content when the drawer
    // opens
    mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    _initMenu();
    mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
    mDrawer.setDrawerListener(mDrawerToggle);

}

private void _initMenu()
{
    NsMenuAdapter mAdapter = new NsMenuAdapter(this);

    // Add Header
    mAdapter.addHeader(R.string.ns_menu_main_header);

    // Add first block

    menuItems = getResources().getStringArray(R.array.ns_menu_items);
    String[] menuItemsIcon = getResources().getStringArray(R.array.ns_menu_items_icon);

    int res = 0;
    for (String item : menuItems)
    {

        int id_title = getResources().getIdentifier(item, "string", this.getPackageName());
        int id_icon = getResources().getIdentifier(menuItemsIcon[res], "drawable", this.getPackageName());

        NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
        // if (res==1) mItem.counter=12; //it is just an example...
        // if (res==3) mItem.counter=3; //it is just an example...
        mAdapter.addItem(mItem);
        res++;
    }

    mAdapter.addHeader(R.string.ns_menu_main_header2);

    mDrawerList = (ListView) findViewById(R.id.drawer);
    if (mDrawerList != null)
        mDrawerList.setAdapter(mAdapter);

    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

}

@Override
protected void onPostCreate(Bundle savedInstanceState)
{
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mDrawerToggle.syncState();
}

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

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.control_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
    // If the nav drawer is open, hide action items related to the content
    // view
    boolean drawerOpen = mDrawer.isDrawerOpen(mDrawerList);
    menu.findItem(R.id.action_keyboard).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    /*
     * The action bar home/up should open or close the drawer.
     * ActionBarDrawerToggle will take care of this.
     */
    if (mDrawerToggle.onOptionsItemSelected(item))
    {
        return true;
    }

    // Handle your other action bar items...
    return super.onOptionsItemSelected(item);
}

private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle
{

    public CustomActionBarDrawerToggle(Activity mActivity, DrawerLayout mDrawerLayout)
    {
        super(mActivity, mDrawerLayout, R.drawable.ic_drawer, R.string.ns_menu_open, R.string.ns_menu_close);
    }

    @Override
    public void onDrawerClosed(View view)
    {
        getSupportActionBar().setTitle(getString(R.string.ns_menu_close));
        supportInvalidateOptionsMenu(); // creates call to
                                        // onPrepareOptionsMenu()
    }

    @Override
    public void onDrawerOpened(View drawerView)
    {
        getSupportActionBar().setTitle(getString(R.string.ns_menu_open));
        supportInvalidateOptionsMenu(); // creates call to
                                        // onPrepareOptionsMenu()
    }
}

private class DrawerItemClickListener implements ListView.OnItemClickListener
{

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        Intent intent = new Intent(MainActivity.this, Tutorial.class);
        startActivity(intent);

    }

}

 }

SecondActivity

 public class Tutorial extends MainActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.help);
    }

}
like image 609
AruLNadhaN Avatar asked Jan 28 '14 12:01

AruLNadhaN


People also ask

How do I get navigation drawer in all activity?

The user can view the navigation drawer when they swipe the activity's screen from the left edge of the android device. A user can also find it from the activity, by tapping the app icon (also known as the “hamburger” menu) in the action bar.

Can we use activity in navigation drawer?

As for how to switch between activities via the navigation drawer, you can just set up new intents within your selectItem() method: private void selectItem(int position) { // Handle Navigation Options Intent intent; switch (position) { case 0: intent = new Intent(currentActivity, NewActivity.

How do you call a navigation drawer from another activity flutter?

Basically Each Activity has its own actionBar and each actionbar can use own Navigation Drawer. So If You want to same navigation Drawer. You can use Fragment. You can make MainActivity has Navigation Drawer and Use FrameLayout in Mainactivity Then Replace Fragment.


3 Answers

Here is my implementation.. hope it help

FIRST, this POST is concept.

SECOND, this is also the KEY one.

FINALLY, Here is combination of all answer in one place


BASE ACTIVITY

This is a base activity for all other activity

You can extends Activity or FragmentActivity or etc. base on your requirement.

Navigation Drawer setup here for one time.

public class BaseActivity extends FragmentActivity {

    protected DrawerLayout mDrawer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.base_layout);

        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        //This is about creating custom listview for navigate drawer
        //Implementation for NavigateDrawer HERE !
        ArrayList<DrawerListItem> drawerListItems = new ArrayList<DrawerListItem>();
        drawerListItems.add(new DrawerListItem(0,"AIR° DEVICES"));
        drawerListItems.add(new DrawerListItem(1,"A/C Device [1]"));
        drawerListItems.add(new DrawerListItem(1,"A/C Device [2]"));
        drawerListItems.add(new DrawerListItem(1,"A/C Device [3]"));
        drawerListItems.add(new DrawerListItem(0,"AIR° FEATURES"));
        drawerListItems.add(new DrawerListItem(2,"SLEEP MODE"));
        drawerListItems.add(new DrawerListItem(2,"TRACKING MODE"));
        drawerListItems.add(new DrawerListItem(2,"SETTINGS"));
        DrawerAdapter mDrawerAdapter = new DrawerAdapter(this, R.layout.drawer_list_header, drawerListItems);
        ListView mDrawerList = (ListView) findViewById(R.id.left_drawer);
        mDrawerList.setAdapter(mDrawerAdapter);
    }

}

BASE ACTIVITY XML

This xml layout is for Navigation Drawer

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

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

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

    </FrameLayout>

    <!-- The navigation drawer -->
    <ListView
            android:id="@+id/left_drawer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="left"
            android:scrollingCache="false"
            android:background="@drawable/drawer_bg"
            android:divider="@null"
            android:choiceMode="singleChoice"/>

</android.support.v4.widget.DrawerLayout>

ALL OTHERS ACTIVITY

Other Activity just extends BaseActivity and define code as below.

The Navigation Drawer will appear for particular activity.

mDrawer is form BaseActivity. it's a protected variable.

public class Screen1 extends BaseActivity

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        //inflate your activity layout here!
        View contentView = inflater.inflate(R.layout.screen1, null, false);
        mDrawer.addView(contentView, 0);

        //Do the rest as you want for each activity
    }

SCREEN 1 XML SAMPLE

Design as you wish it each activity. no more Navigation Drawer Layout !

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

</LinearLayout>

NOTE

In this implementation, The Navigation Drawer doesn't bind with Action Bar. If you wish to do that do it in BaseActivity.Also, This guide is not cover all requirement. It's just a sample.

like image 168
Jongz Puangput Avatar answered Oct 23 '22 08:10

Jongz Puangput


in onCreate of TutorialActivity don't call setContentView instead do this:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    LayoutInflater inflater = (LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View contentView = inflater.inflate(R.layout.help, null, false);
    mDrawer.addView(contentView, 0); 
}

make mDrawer in MainActivity protected. and in R.layout.activity_main_drawer just keep drawer tag and the element with gravity left(or right).

like image 24
vipul mittal Avatar answered Oct 23 '22 09:10

vipul mittal


I made a BaseActivity activity which extends SherlockActivity (or ActionBarActivity if is your case)

public class BaseActivity extends SherlockActivity

Then, make all your activities extends BaseActivity, like:

public class GlossaryActivity extends BaseActivity

Later, you must replace the activity layout with the one that correspond to your activity, I made a method in BaseActivity like that:

protected void replaceContentLayout(int sourceId, int destinationId) {
    View contentLayout = findViewById(destinationId);

    ViewGroup parent = (ViewGroup) contentLayout.getParent();
    int index = parent.indexOfChild(contentLayout);

    parent.removeView(contentLayout);
    contentLayout = getLayoutInflater().inflate(sourceId, parent, false);
    parent.addView(contentLayout, index);
}

I called this method on the onCreate method in each activity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.replaceContentLayout(R.layout.activity_glossary, super.CONTENT_LAYOUT_ID);

}

super.CONTENT_LAYOUT_ID is the FrameLayout of the BaseActivity, and other param is the layout you want replace with

like image 2
Daniel Siguero Avatar answered Oct 23 '22 08:10

Daniel Siguero