从片段访问父活动的数据 [英] Accessing data of parent activity from a fragment

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

问题描述

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

What is the best way to access data members of an activity from its fragment Some ways which I know include -

  1. 在Activity将要实现的Fragment中创建一个接口.该界面将提供访问Activity数据成员的方法.

  1. Create an interface in the Fragment which the Activity will implement. The interface will have the methods to access data members of the Activity.

使用片段中的((Activity)getActivity).getXXX()直接访问.

Directly access using ((Activity)getActivity).getXXX() from the fragment.

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

Pass the data members or custom parcelable class to newInstance method of the fragment and set the fragment arguments as the class for e.g. -

Bundle args = new Bundle();

Bundle args = new Bundle();

args.putInt("num",num);

args.putInt("num", num);

f.setArguments(args);

f.setArguments(args);

然后我们可以使用getArguments()

and later we can get the arguments using getArguments()

哪种方法最好,每种方法都有哪些缺点?

Which method is the best and what are the drawbacks of each?

推荐答案

实际上,第一种和第三种方法的组合是最好的.应该不惜一切代价避免第二个,因为这将Fragment与特定的 Activity 紧密结合在一起.这将破坏 Fragments 的主要优点之一,即能够在不同的 Activity (即插即用)中使用它.

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).

关于第一种和第三种方法.-第一个是通常如何从 Fragment Activity 进行通信.-第三个是通常如何实例化 Fragment ,同时将 Activity 中的数据传递给它.当您已经运行了 Fragment 的实例时,您将不得不依靠第一种方法.

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.

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

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