我的应用程序中的onBackPressed()实现存在问题。我有一个带有differents标签的片段。用户可以使用导航视图和后退按钮在片段之间导航。一切都按预期工作,但FragmentTransaction如下所示:
初始片段-> A-> B-> C-> A
当我使用后退按钮返回时,我要实现的行为是A-> C-> B->初始。
相反,我得到A-> B-> C-> A->初始
如何完成我想要的行为?
这是我到目前为止所拥有的:
private int backStackEntries = 0;
public void onBackPressed() {
Log.d(TAG,"Number of fragments in back: "+backStackEntries);
NewsListFragment fragment = (NewsListFragment) getSupportFragmentManager().findFragmentByTag(currentFrag);
backStackEntries-=1;
if(backStackEntries<0)
backStackEntries = 0;
if(fragment.getTag().equals(News_TAG[0])){
if(fragment.getParserMaker().isRunning()){
moveTaskToBack(true);
}
else{
finish();
}
}
else{
currentFrag = getSupportFragmentManager().getBackStackEntryAt(backStackEntries).getName();
getSupportFragmentManager().beginTransaction()
.hide(fragment)
.show(getSupportFragmentManager().findFragmentByTag(currentFrag))
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
}
private void makeFragmentTransaction(String[] urls, int item,String _TAG) {
Bundle bundle = new Bundle();
bundle.putStringArray("urls", urls);
NewsListFragment newsFragment = (NewsListFragment) getSupportFragmentManager().findFragmentByTag(_TAG);
if(newsFragment == null){
newsFragment = new NewsListFragment();
}
newsFragment.setArguments(bundle);
if(currentFrag == null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, newsFragment, _TAG)
.addToBackStack(_TAG)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
currentFrag = _TAG;
}
else if(!newsFragment.isAdded()){
getSupportFragmentManager().beginTransaction()
.hide(getSupportFragmentManager().findFragmentByTag(currentFrag))
.add(R.id.container,newsFragment,_TAG)
.addToBackStack(_TAG)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
currentFrag = _TAG;
backStackEntries+=1;
}
else if(!currentFrag.equals(_TAG)){
getSupportFragmentManager().beginTransaction()
.hide(getSupportFragmentManager().findFragmentByTag(currentFrag))
.show(newsFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
backStackEntries+=1;
currentFrag = _TAG;
}
navigationView.setCheckedItem(item);
drawerLayout.closeDrawers();
}
添加最后一个 backStackEntries + = 1; 会产生奇怪的行为,而删除该行会导致交易,但会导致另一个交易问题:
初始(返回)-> B-> C
按下后退按钮:C->初始
我也尝试过这样的交易:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, newsFragment, _TAG)
.addToBackStack(_TAG)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
currentFrag = _TAG;
像这样的onBackPressed:
NewsListFragment fragment = (NewsListFragment) getSupportFragmentManager().findFragmentByTag(currentFrag);
if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
getSupportFragmentManager().popBackStack();
} else {
if (fragment.getParserMaker().isRunning()) {
moveTaskToBack(true);
} else {
finish();
}
}
这也会导致不良行为,并且popBackStack()会删除我不想做的片段。
答案 0 :(得分:0)
我也遇到了同样的问题,我通过为片段实现自己的历史堆栈来解决了这个问题。每当我想向堆栈中添加一个片段时,我都会浏览堆栈并删除与我要添加的片段具有相同类的片段(如果有的话)