How to open Side bar on icon click in Android?

南笙酒味 提交于 2019-12-01 00:30:29

Using the Toolbar component should be fairly easy to achieve this by using a similar code to this:

    Toolbar toolbar = (Toolbar) findViewById(R.id.home_toolbar);
    toolbar.inflateMenu(R.menu.menu_home);
    toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            if (item.getItemId() == R.id.action_settings) {
                mDrawerLayout.openDrawer(Gravity.RIGHT); // where mDrawerLayout is your android.support.v4.widget.DrawerLayout in your activity's xml layout.
            }
            return false;
        }
    });

EDIT:

The key component here is the menu_home.xml file which goes to your res/menu folder. You can add your desired menu item there, customize it's icon and even more, add as many items as you'd like to have on the right side of the toolbar(Obviously handle the openDrawer() method on whichever menu item you need - the recommended one is the rightmost though).

Use the openDrawer() method.

private DrawerLayout mDrawerLayout;
...
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
...
mDrawerLayout.openDrawer(Gravity.END); // or whatever gravity the of the drawer you want to open

Use Activity's onOptionsItemSelected(MenuItem menuItem) method:

First of all, keep the reference to your DrawerLayout in a class field:

DrawerLayout drawerLayout;

Somewhere in onCreate put this:

drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout)

And implement the method:

@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    // if you want the default back/home hamburger menu item just put android.R.id.home instead
    if (menuItem.getItemId() == R.drawable.icon_navigation) { 
        drawerLayout.openDrawer(GravityCompat.END);
    }
    return super.onOptionsItemSelected(menuItem);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!