从片段访问活动的数据成员的最佳方法是什么 我知道的一些方法包括 -
在Frag中创建一个活动将实现的接口。该接口将具有访问活动数据成员的方法。
直接从片段中使用((Activity)getActivity).getXXX()进行访问。
将数据成员或自定义parcelable类传递给片段的newInstance方法,并将片段参数设置为例如类的类。 -
Bundle args = new Bundle();
args.putInt(“num”,num);
f.setArguments(参数);
以后我们可以使用getArguments()
哪种方法最好,每种方法的缺点是什么?
答案 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.