为什么使用捆绑包将数据传递给碎片? [英] Why use bundle to pass data to fragment?

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

问题描述

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

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文档状态:

每个片段都必须有一个空的构造函数,因此可以在恢复其活动状态时实例化它.强烈建议子类不要使用带有参数的其他构造函数,因为在重新实例化片段时将不会调用这些构造函数;取而代之的是,参数可以由调用者使用setArguments(Bundle)提供,然后由Fragment使用getArguments()进行检索.

Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments().

这就是为什么最好使用捆绑包并以这种方式设置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.

应用程序通常不应实现构造函数.可以在准备使用片段的地方运行的第一个应用程序代码是在onAttach(Activity)中,该片段实际上与其活动相关联.某些应用程序可能还希望实现onInflate(Activity,AttributeSet,Bundle)以从布局资源中检索属性,尽管此处应格外小心,因为这种情况是由于片段附加到其活动上而发生的.

Applications should generally not implement a constructor. The first place application code can run where the fragment is ready to be used is in onAttach(Activity), the point where the fragment is actually associated with its activity. Some applications may also want to implement onInflate(Activity, AttributeSet, Bundle) to retrieve attributes from a layout resource, though should take care here because this happens for the fragment is attached to its activity.

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

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