“返回按钮"使用getSupportActionbar和appcompat v7工具栏 [英] "Back button" using getSupportActionbar and appcompat v7 toolbar
问题描述
我正在使用Appcompat V7库中的新工具栏,并且正在制作带有导航抽屉和片段的应用程序.
I'm using the new toolbar from the Appcompat V7 library and I'm making an application with navigation drawer and with fragments.
在某些片段中,我不想显示汉堡包图标,而是显示箭头...很好,我这样做是这样的:
In some fragments I don't want to show the hamburger icon but the arrow instead... That is fine I did this in this way:
mDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
我的问题是:如何或在何处设置主页按钮lisener或需要听后退"按钮的内容? 我想调用主要的backpressed方法,并用汉堡包图标调回导航抽屉图标.
My question is that: How or where i need to set up the home button lisener or what i need to listen for the "back" button ? I want to call the main backpressed method and to set back the navigation drawer icon with the hamburger icon..
推荐答案
您可以这样做:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
toolbar = (Toolbar)findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
setUpNavigationDrawer();
getFragmentManager().addOnBackStackChangedListener(backStackListener); // listen to the backstack of the fragment manager
}
定义onBackSTackChangedListener:
Define the onBackSTackChangedListener:
private FragmentManager.OnBackStackChangedListener backStackListener = new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
setNavIcon();
};
}
根据片段的后堆栈设置图标:
Set the icon according to your fragment's backstack:
protected void setNavIcon() {
int backStackEntryCount = getFragmentManager().getBackStackEntryCount();
drawerToggle.setDrawerIndicatorEnabled(backStackEntryCount == 0);
}
按下抽屉图标时检测:
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.isDrawerIndicatorEnabled() && drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case x:
return true;
default:
return false;
}
}
并按下向上按钮:
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
这对我有用.祝你好运.
This works for me. Good luck.
这篇关于“返回按钮"使用getSupportActionbar和appcompat v7工具栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!