问题描述
在我的应用中,我遇到这样的问题.请注意,我正在处理片段,我也有抽屉.
In my app I have problem like this. Note that I'm working with fragments and I have drawer too.
这是MainActivity中抽屉打开/关闭的方法.
That's the method in my MainActivity for drawer open/close.
public void drawerInit() {
toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer);
view = findViewById(R.id.mainView);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
float moveFactor = (drawerView.getWidth() * slideOffset);
view.setTranslationX(moveFactor);
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
drawer.addDrawerListener(toggle);
toggle.syncState();
}
示例I有3个片段(F1,F2,F3).F1是我的主要片段,可以在其中打开和关闭抽屉.打开F2或F3片段时,需要将抽屉图标更改为后退箭头.我已经成功完成了这一部分,但是问题是当我单击此后退箭头时,它打开了导航抽屉,而不是返回.那我该如何修复这部分呢?
Example I have 3 fragments (F1, F2, F3). F1 is my main fragment where I can open and close the drawer. When I'm opening F2 or F3 fragments, I need to change the drawer icon to back arrow. I'm doing this part successfully, but the problem is when I'm clicking on this back arrow, that opens the navigation drawer instead of going back. So how can I fix this part?
在这里,我将图标更改为片段中的后退箭头.
Here the part, where I'm changing the icon to back arrow in fragment.
((AppCompatActivity) getActivity()).getSupportActionBar().show();
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
推荐答案
添加您的活动
public void crateMenuButton(){
toggle.setDrawerIndicatorEnabled(true);
if(toolbarDrawable == null) {
toolbarDrawable = toolbar.getNavigationIcon();
}
toolbar.setNavigationIcon(toolbarDrawable);
invalidateOptionsMenu();
toggle.syncState();
}
public void createBackButton() {
toggle.setDrawerIndicatorEnabled(false);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//if the drawerToggle is disabled, fall off to the home button action
if (!toggle.isDrawerIndicatorEnabled()) {
// pop fragment here
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
}
} else {
if (drawerLayout.isDrawerOpen(navigationView)) {
drawerLayout.closeDrawer(navigationView);
} else {
drawerLayout.openDrawer(navigationView);
}
}
}
});
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white));
}
下载后退箭头
然后根据需要从片段中调用
((YourActivity) getActivity()).createBackButton();
OR
((YourActivity) getActivity()).crateMenuButton();
这篇关于ActionBar的“后退"按钮可打开抽屉,而无需后退的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!