【发布时间】:2011-09-05 07:54:55
【问题描述】:
是否可以在片段之间切换而无需一直重新创建它们?如果有,怎么做?
In the documentation 我找到了一个如何替换 Fragments 的示例。
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
但我不想每次需要时都从头开始创建片段。
我还发现了 this example 的隐藏/显示片段:
// The content view embeds two fragments; now retrieve them and attach
// their "hide" button.
FragmentManager fm = getFragmentManager();
addShowHideListener(R.id.frag1hide, fm.findFragmentById(R.id.fragment1));
addShowHideListener(R.id.frag2hide, fm.findFragmentById(R.id.fragment2));
但是如何在 XML 文件之外创建一个带有 ID 的片段?
我认为这可能与this question 有关,但没有答案。 :/
非常感谢您, 水母
编辑:
我现在就是这样:
Fragment shown = fragmentManager.findFragmentByTag(shownFragment);
//...
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (shown != null) fragmentTransaction.hide(shown);
//switch statetement for menu selection, just one example:
SettingsFragment set = (SettingsFragment) fragmentManager.findFragmentByTag(SET);
Toast.makeText(this, "Settings:" + set, Toast.LENGTH_LONG).show();
if (set == null)
{
set = new SettingsFragment();
fragmentTransaction.add(R.id.framelayout_content, set, SET);
}
else fragmentTransaction.show(set);
shownFragment = SET;
fragmentTransaction.commit();
如果我调用设置,然后调用其他内容,然后返回设置,吐司首先给我“null”,然后给我“Settings:SettingsFragment{40ef...”。
但是,如果我将 fragmentTransaction.add(R.id.framelayout_content, set, SET); 替换为 fragmentTransaction.replace(R.id.framelayout_content, set, SET);,我会不断收到“null”、“null”、“null”...所以它似乎无法通过标签找到 Fragment。
编辑2:
添加fragmentTransaction.addToBackStack(null); 成功了。 :)
这节省了整个隐藏/记忆哪个片段被显示的部分,所以我认为这是最优雅的解决方案。
我发现 this 教程对这个主题很有帮助。
编辑3:
看着我的代码,我意识到我可以去掉一些部分,所以我把它改成了:
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (shown != null) fragmentTransaction.hide(shown);
Settings set = (Settings) fragmentManager.findFragmentByTag(SET);
if (set == null) set = new Settings();
fragmentTransaction.replace(R.id.framelayout_content, set, SET);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
但是,这调用了 IllegalStateException: Fragment already added,与 here 非常相似。有没有简单的方法来防止这种情况?否则我想我可能会切换回隐藏/显示位。
【问题讨论】:
标签: android android-3.0-honeycomb android-fragments