从片段访问父活动的数据

时间:2016-08-23 15:05:50

标签: android android-fragments

从片段访问活动的数据成员的最佳方法是什么 我知道的一些方法包括 -

  1. 在Frag中创建一个活动将实现的接口。该接口将具有访问活动数据成员的方法。

  2. 直接从片段中使用((Activity)getActivity).getXXX()进行访问。

  3. 将数据成员或自定义parcelable类传递给片段的newInstance方法,并将片段参数设置为例如类的类。 -

    Bundle args = new Bundle();

    args.putInt(“num”,num);

    f.setArguments(参数);

    以后我们可以使用getArguments()

  4. 获取参数

    哪种方法最好,每种方法的缺点是什么?

1 个答案:

答案 0 :(得分:1)

Actually the combination of the first and third method is the best. The second one should be avoided at all cost since this strongly couples the Fragment to a specific Activity. This will defeat one of the main advantages of Fragments namely being able to use it in different Activities (plug and play).

As for the first and third method. - The first one is how you will usually communicate from the Fragment to your Activity. - The third one is how you'll usually instantiate your Fragment while passing data to it from your Activity. When you already have an instance of your Fragment running you'll have to fall back on your first method.