本文介绍了为什么使用捆绑包将数据传递给碎片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个始终可见的片段.我不明白为什么我应该使用捆绑包将数据从活动传递给它.

I have a fragment that is always visible. I don't understand why I should use bundles to pass data to it from activity.

这里的大多数问题都建议使用这种数据传递方法:

Most of the questions here recommend this method of passing data:

Bundle bundle=new Bundle();
bundle.putString("name", "From Activity");
Fragmentclass fragobj=new Fragmentclass();
fragobj.setArguments(bundle);

我更喜欢在活动的OnCreate函数中创建Fragment对象,然后使用该对象显示fragment(FragmentTransaction.add).由于我对这个片段有所了解,因此我可以在其中创建创建函数showName(),并从如下活动中调用它:

I prefer creating Fragment object in OnCreate function of activity and then use this object to display fragment(FragmentTransaction.add). As I have refence to this fragment I can create create function showName() in it and call it from activity like that:

myFragment.showName("name");

这种方法有什么问题吗?

Is there anything wrong with this approach?

推荐答案

Android文档状态:

这就是为什么最好使用捆绑包并以这种方式设置Fragment的参数的原因,当重新实例化片段时,系统更容易恢复其值.

That's why it's better to use a bundle and set the parameters of the Fragment this way, it's easier for the system to restore its values when the fragment is re-instantiated.

现在,我将不使用myFragment.showName("name");,因为您不知道该片段的生命周期是否已经结束(附加到活动中并放大了视图),因此,我将在其中调用showName("name") onActivityCreatedonViewCreated回调.

Now, I wouldn't use myFragment.showName("name"); because you don't know if the lifecycle of the fragment has already finished (attached to the activity and inflated the views), so instead, I would call the showName("name") in the onActivityCreated or onViewCreated callbacks.

这篇关于为什么使用捆绑包将数据传递给碎片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 23:58