Android:Fragments backStack [英] Android: Fragments backStack
问题描述
我正在尝试在调用方法时加载新片段.此方法创建一个新片段并替换"另一个片段:
Im trying to load an new fragment when a method is called. This method creates a new fragment and "replaces" the other fragment:
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);
}
}
这很好用,直到我回去.最后一个片段,当我回去时应该删除.在我要对活动实施方法之前
This works fine, until i go back. The last fragment, should be removed when i go back. Before i'm going to implement methods on the activities
public void onBackPressed(){}
要删除最后一个片段,我想知道我是否正确处理了片段更改.看起来我在这里遗漏了一些东西..
to remove the last fragment, i want to know if i handle the fragment change correctly. It looks like i'm missing something here..
推荐答案
如果你真的想替换片段,那么使用 replace() 方法而不是执行 remove() 和 add().
If you really want to replace the fragment then use replace() methode instead of doing a remove() and an add().
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(..............);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
不要忘记执行 addToBackStack(null) 这样您之前的状态将被添加到 backstack 中,允许您使用后退按钮返回.
Don't forget to do the addToBackStack(null) so your previous state will be added to the backstack allowing you to go back with the back button.
另一个很好的来源是http://developer.android.com/guide/components/fragment.html(搜索 replace() 函数).
Another good source is http://developer.android.com/guide/components/fragments.html (search for replace() function).
这篇关于Android:Fragments backStack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!