如何避免碎片娱乐? [英] How to avoid Fragment recreation?

查看:94
本文介绍了如何避免碎片娱乐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个 Fragments F1 F2 .我使用以下代码从 Activity 中打开第一个 Fragment F1 :

I have 2 Fragments F1 and F2. I open the first Fragment F1 from the Activity using the following code:

MyFragment f1 = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("GameLevelType", "Learn");
dialog.setArguments(bundle);
FragmentTransaction gameTransaction = getSupportFragmentManager().beginTransaction();
gameTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
gameTransaction.add(android.R.id.content, f1).addToBackStack(null).commit();

然后从 Fragment F1 中使用以下代码打开另一个 Fragment F2 :

Then from Fragment F1 I am opening another Fragment F2 using below code:

MySecondFragment f2 = new MySecondFragment();
            Bundle bundle = new Bundle();
            FragmentTransaction transaction = ((AppCompatActivity) context).getSupportFragmentManager().beginTransaction();
            bundle.putInt("CurrentPosition", getAdapterPosition());
            bundle.putIntArray("x", kolamTracingGameList.get(getAdapterPosition()).getX());
            bundle.putIntArray("y", kolamTracingGameList.get(getAdapterPosition()).getY());
            bundle.putInt("Level", (getAdapterPosition() + 1));
            bundle.putString("GameType", "Kolam");
            fragment.setArguments(bundle);
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            transaction.replace(android.R.id.content, f2).addToBackStack(null).commit();

问题是当我关闭 Fragment F2 Fragment F1 出现在前台时.正在重新创建整个 F1 (再次调用 onViewCreated()).我不希望 F1 在前景方面再次被创建.

Problem is when I close Fragment F2 and Fragment F1 comes to foreground. Whole F1 is recreating(onViewCreated() is called again). I don't want F1 to get recreated again when it comes to foreground.

推荐答案

对于第二个片段,请使用add而不是replace.

For the second fragment use add instead of replace.

replace -删除现有片段并添加一个新片段.在片段F2中按下后退"按钮时,将再次调用oncreateView中的片段.

replace- removes the existing fragment and adds a new fragment.when the back button is pressed in fragment F2,fragment in oncreateView is called again.

add -保留现有片段并添加一个新片段,这意味着现有片段将处于活动状态,并且不会处于暂停"状态.在片段F2中按下后退"按钮时,没有一个片段F1的方法再次被调用.

add -retains the existing fragments and adds a new fragment that means existing fragment will be active and they wont be in 'paused'.when the back button is pressed in fragment F2,none of the methods of the fragment F1 are called again.

transaction.add(android.R.id.content, f2).addToBackStack(null).commit();

这篇关于如何避免碎片娱乐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆