Android:片段backStack
我试图加载一个新的片段,当一个方法被调用。 这个方法创build一个新的片段并“replace”另一个片段:
private void showTestFragment(Fragment oldFragment, boolean addBackStack, BaseAdapter adapter, int position) { Cursor cursor = (Cursor)adapter.getItem(position); if(cursor != null){ int idx = cursor.getColumnIndexOrThrow(Episode._ID); long rowId = cursor.getLong(idx); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); if(oldFragment != null){ Log.i(TAG, "Removing the old fragment"); fragmentTransaction.remove(oldFragment); } TestFragment testFragment = new TestFragment(); testFragment.setId(rowId); fragmentTransaction.add(android.R.id.content, testFragment); if(addBackStack){ Log.i(TAG, "Added to the backstack"); fragmentTransaction.addToBackStack(TAG); } fragmentTransaction.commit(); Fragment f = getFragmentManager() .findFragmentById(R.id.index); Log.i(TAG, "after commit, frag is "+ f); } }
这工作正常,直到我回去。 当我回去时,最后一个片段应该被删除。 在我要执行活动的方法之前
public void onBackPressed(){}
删除最后一个片段,我想知道如果我正确处理片段更改。 看起来我在这里错过了一些东西
如果你真的想要replace片段,那么使用replace()方法而不是执行remove()和add()。
FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(..............); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit();
不要忘记执行addToBackStack(null),以便将以前的状态添加到backstack中,以便您可以返回后退button。
另一个好的来源是http://developer.android.com/guide/components/fragments.html (searchreplace()函数)。
只要先删除,然后调用super.onBackPressed
public void onBackPressed(){ // here remove code for your last fragment super.onBackPressed(); }
//lets wait for systems back to finish super.onBackPressed(); //here we believe a fragment was popped, so we need to remove the fragment from ourbackstack if(fragmentBackStack.size()>0) { Log.d("custombackstack","before back: "+fragmentBackStack.size()+" current:"+fragmentBackStack.peek()); fragmentBackStack.pop(); } //after popping is the size > 0, if so we set current fragment from the top of stack, otherwise we default to home fragment. if(fragmentBackStack.size()>0) { Log.d("custombackstack","after back: "+fragmentBackStack.peek()); currentFragment = fragmentBackStack.peek(); } else { //back stack empty currentFragment = HOME_FRAGMENT; }