I have implemented Hamburger
bar with App toolbar
and both of them are working fine. Following is the snapshot of toolbar
and hamburger
bar:
Hamburger bar
I can open this bar by sliding it but I also want to make it open by clicking on drawable icon (right top corner icon). How can i do that?
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
drawerFragment.setDrawerListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
I don't think so that I need to do some changes in layout
files. What do I have to add in MainActivity
file to make it possible?
I am newbie in Android
code. Any help will be appreciable.
Use
Activity
'sonOptionsItemSelected(MenuItem menuItem)
method:First of all, keep the reference to your
DrawerLayout
in a class field:Somewhere in onCreate put this:
And implement the method:
Using the Toolbar component should be fairly easy to achieve this by using a similar code to this:
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.