如何在Android中打开图标上的边栏? [英] How to open Side bar on icon click in Android?
问题描述
我已经用App toolbar
实现了Hamburger
栏,并且它们都工作正常.以下是toolbar
和hamburger
bar的快照:
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?
@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);
}
我不认为我需要在layout
文件中进行一些更改.我必须在MainActivity
文件中添加些什么才能使其成为可能?
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?
我是使用Android
代码的新手.任何帮助都将是可贵的.
I am newbie in Android
code. Any help will be appreciable.
推荐答案
使用工具栏组件应该很容易实现,方法是使用与此类似的代码:
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;
}
});
这里的关键组件是 menu_home.xml 文件,该文件进入您的res/menu文件夹.您可以在此处添加所需的菜单项,自定义其图标,甚至更多,在工具栏的右侧添加任意数量的项(显然,可以在所需的任何菜单项上处理openDrawer()方法-推荐之一是最右边的).
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).
这篇关于如何在Android中打开图标上的边栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!