题
我正在使用Android Studio模板中的导航抽屉.我想在我的一些片段中使用UP按钮(箭头)插入“汉堡”按钮.
我使用AppCompatActivity.
我使用此代码显示UP按钮箭头:
public void UseUpButton(boolean value) {
ActionBar actionBar = getSupportActionBar();
if (value) {
actionBar.setDisplayHomeAsUpEnabled(false);
toggle.setDrawerIndicatorEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
} else {
toggle.setDrawerIndicatorEnabled(true);
}
}
试过的变种:
但是我无法点击这个按钮.我试过一些方法:
使用onOptionsItemSelected
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("WTF", "menu");
switch (item.getItemId())
{
case android.R.id.home:
getFragmentManager().popBackStack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
我添加了getSupportActionBar().setHomeButtonEnabled(true);到我的Activity :: onCreate,但当我按下向上按钮时,onOptionsItemSelected没有被调用,当我按下菜单项时,它正常工作.
使用ActionBarToggle OnClickListener
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
toggle.setToolbarNavigationClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
}
});
但是这种方法也没有按下Up按钮.
结论:
那么,我怎样才能抓住向上按钮按下事件?
解决方法:
几天前我在某个地方发现了这个……
在我的代码中,我初始化ActionBarDrawerToggle.它有一些构造函数,但我对此感兴趣:
1
public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout,
@StringRes int openDrawerContentDescRes,
@StringRes int closeDrawerContentDescRes) {
this(activity, null, drawerLayout, null, openDrawerContentDescRes,
closeDrawerContentDescRes);
}
2
public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout,
Toolbar toolbar, @StringRes int openDrawerContentDescRes,
@StringRes int closeDrawerContentDescRes) {
this(activity, toolbar, drawerLayout, null, openDrawerContentDescRes,
closeDrawerContentDescRes);
}
看一看:第二个构造函数有工具栏工具栏参数.
如果你想处理UP BUTTON事件,请不要使用第二个CONSTUCTOR并先使用.
例:
toggle = new ActionBarDrawerToggle(
this,
drawer,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
getSupportActionBar().setHomeButtonEnabled(true);
setHomeButtonEnabled很重要,没有这个你就看不到汉堡包或者Up按钮了.