是否可以在碎片之间切换而不必一直重新创建碎片?如果是这样,怎么样?Android Honeycomb:如何更改FrameLayout中的碎片,而不重新创建它们?
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();
如果我调出设置,然后再回到设置,敬酒先给我“空”,然后“设置:SettingsFragment {40ef ...”秒。
但是,如果我将fragmentTransaction.add(R.id.framelayout_content, set, SET);
替换为fragmentTransaction.replace(R.id.framelayout_content, set, SET);
我总是收到“null”,“null”,“null”...所以它似乎没有找到Fragment by标记。
EDIT2:
添加fragmentTransaction.addToBackStack(null);
的伎俩。 :) 这节省了整个隐藏/记忆哪个片段显示部分,所以我想这是最优雅的解决方案。
我发现this教程对这个话题很有帮助。
EDIT3:
看着我的代码,我意识到我可以摆脱一些地方,所以我把它改为:
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。有没有简单的方法来防止这种情况?否则,我想我可能会切换回隐藏/显示位。
我想根据菜单选择在碎片之间进行切换,所以如果你再次选择相同的菜单项,我想再次显示相同的碎片。通过标签找到片段 – jellyfish 2011-06-01 08:37:31
然后,我会坚持片段在内存中,并进行替换。我不明白为什么你需要找到片段,因为你可以跟踪当前的菜单选择,并知道什么片段是然而,当选择一个新的菜单项时,我不明白为什么找到片段标签不应该工作(我已经做了类似于DialogFragment的内容,如果内存服务,API中的DialogFragment示例演示。 – PJL 2011-06-01 19:55:41
那么,你是否建议我应该在我的课堂中为每个片段保留一个参考场?对于另一部分,请参阅我的编辑。 – jellyfish 2011-06-06 08:51:34