我有一个关于在 Controller Activity 中的 fragment 内容之间共享信息的更好方式的内部讨论。在第一种经典方式中,您可以在要替换 fragment 时设置参数,如下所示:
//Just now i'm inside Fragment 1 and i'll navigate to Fragment 2
Fragment newFragment = getFragmentManager().findFragmentByTag(Fragment2.TAG);
Bundle b = new Bundle();
b.putBoolean("test1", true);
// Create new fragment and transaction
if(newFragment==null)
newFragment = Fragment2.newInstance(b);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)//.setCustomAnimations(R.anim.enter_anim, R.anim.exit_anim)
.replace(R.id.fragment_place, newFragment, Fragment2.class.getName())
.addToBackStack(newFragment.getClass().getName())
.commit();
newInstace 方法按照我上面的意思执行,因此,使用 setArguments:
public static Fragment2 newInstance(Bundle arguments){
Fragment2 f = new Fragment2();
if(arguments != null){
f.setArguments(arguments);
}
return f;
}
但 Fragment1 和 Fragment2 它们都在 ControllerActivity 中,所以我还可以考虑第二种方法,通过在 ControllerActivity 中声明属性,将 Fragment1 中获得的信息共享给 Fragment2,这样我就可以做到(之前在 Activity )在任何 fragment 中如下所示:
编辑
public class ControllerActivity extends FragmentActivity{
int value = 5;
...
然后,在我的 fragment 中:
((SplashActivity)getActivity()).value = 10; //i can assign or recover value when i desire
我的问题是第二种方式会带来哪些不便。
最佳答案
使用第二种方式编写代码很快。但问题是您必须将一般的 Activity
转换为更具体的 SplashActivity
,其中存在 value
变量。如果您想将 Fragment 与另一个 Activity 一起使用,或者您希望 Fragment 成为通用 UI 组件,您必须使用 interface
来传递数据。
如评论中所述,以下链接提供了有关接口(interface)/回调
方法的更多详细信息:
希望这能回答您的问题。
关于Android Fragments 共享信息的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30191060/