从活动设置片段的参数 [英] Set arguments of fragment from activity

查看:19
本文介绍了从活动设置片段的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将参数从我的活动传递到嵌入到活动中的片段.片段静态嵌入在 xml 布局中.我试着像这样调用 setArgument():

I want to pass arguments from my activity to a fragment, embedded into the activity. Fragment is embedded statically in xml layout. I tried to call setArgument() like this:

setContentView(R.layout.detail_activity);
DetailFragment detailFragment = (DetailFragment) getFragmentManager().findFragmentById(R.id.detailFragment);
detailFragment.setArguments(getIntent().getExtras());

但是已经太晚了,因为 setArguments 必须在片段创建后立即调用.我唯一看到的是 getArguments() 并更改了包.有什么更好的方法吗?

but it is already too late, because setArguments has to be called immediately after fragment's creation. The only was I see it to getArguments() and the change the bundle. Any better way?

推荐答案

AFAIK,当您将片段嵌入 XML 时,您不能像那样使用 setArguments().如果它很重要,你最好动态添加片段.但是,如果您真的希望通过 XML 嵌入片段,则可以通过不同的方式传递该数据.

AFAIK, you can't use setArguments() like that when you embed the fragment within XML. If it's critical, you'd be better off dynamically adding the fragment instead. However if you truly want the fragment to be embedded via XML, there are different ways you can pass along that data.

  1. 让 Activity 实现片段的事件侦听器.然后让片段在创建时或需要时从 Activity 请求所需的参数.与 Fragment 通信
  2. 创建可以与片段一起嵌入到 xml 中的自定义属性.然后在fragment的inflation过程中,解析自定义属性来获取它们的数据.自定义片段属性
  3. 在片段中创建公共设置器并让活动直接使用它们.如果在片段的 onCreate() 方法之前设置它们很重要,那么从活动的 onAttachFragment() 方法中进行设置.
  1. Have the Activity implement the fragment's event listener. Have the fragment then request the required parameters from the Activity at creation or whenever needed. Communication with Fragment
  2. Create custom attributes that can be embedded in xml along with the fragment. Then during fragment's inflation process, parse the custom attributes to obtain their data. Custom fragment attributes
  3. Create public setters in the fragment and have the activity use them directly. If it's critical to set them prior to the fragment's onCreate() method, then do it from the activity's onAttachFragment() method.

这篇关于从活动设置片段的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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