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

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

问题描述

我想从我的活动片段,嵌入到活动传递参数。片段是在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,你不能使用 setArguments()一样,当你嵌入到XML片段。如果它的关键,你最好关闭动态添加的片段来代替。但是,如果你真的想要的片段通过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. 有活动落实片段的事件监听器。有片段然后请求所需的参数从活动在创建或当需要。 <一href="http://developer.android.com/training/basics/fragments/communicating.html#DefineInterface">Communication与片段
  2. 创建可以嵌入在XML随着片段自定义属性。然后,在片段的通货膨胀过程,解析自定义属性,以获得他们的数据。 定制的片断属性
  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天全站免登陆