【问题标题】:Android : How to efficiently send and receive data between Fragment and Activity?Android:如何在 Fragment 和 Activity 之间高效地发送和接收数据?
【发布时间】:2023-03-08 19:16:01
【问题描述】:
我在使用ViewPager 和TabLayout 的活动中使用了两个片段。我想在我的Activity 和我的Fragments 之间发送和接收数据。
我不喜欢使用带有static 变量的类来解决这个问题。有没有更好的方法来完成这项任务而不会丢失大量内存和资源。因为静态数据成员在 app 的整个生命周期中永远不会消亡。所以他们从不释放任何内存块。这对于在三星设备上运行的应用程序来说是一个大问题,或者您可以说限制 RAM 使用的非 root 设备。
【问题讨论】:
标签:
android
performance
android-fragments
android-activity
【解决方案1】:
使用界面。这是 Android 文档的摘录,其中包含有关如何在 Fragment 和 Activity 之间进行通信的示例的详细信息,反之亦然:Define an Interface。
要允许 Fragment 与其 Activity 进行通信,您可以在 Fragment 类中定义一个接口并在 Activity 中实现它。 Fragment 在其 onAttach() 生命周期方法期间捕获接口实现,然后可以调用接口方法以与 Activity 通信。
这使您的Fragment 模块化,并允许您在多个活动中重复使用相同的Fragment。您需要做的就是在新的Activity 中实现interface。
【解决方案3】:
以下是 Fragment 到 Activity 通信的示例:
公共类 HeadlinesFragment 扩展 ListFragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
}