android - 如何在 viewpager 的所有 fragment 中获取相同的子 fragment (具有 recyclerview)实例?

标签 android android-fragments android-recyclerview child-fragment

我遇到了这样一种情况,我的 recyclerview 中包含项目数据,我需要在 viewpager 的所有 fragment (三个)中获取相同的实例以在同一个 recyclerview 上运行。

我做了什么:

我已经将一个单独的 fragment 名称命名为 ItemListFragment,并在列表中使用常用按钮和选项,现在尝试将其作为子 fragment 添加到我的 viewpager fragment 中。我可以将它们添加为子 fragment ,但此时我必须为所有 PretFragment 创建 3 个不同的 ItemListFragment。

请帮助我克服这种情况或建议在所有 3 个 fragment 中使用通用回收列表的任何其他方法。我搜索了 stackoverflow,但没有任何帮助。

这是了解情况的图片:

enter image description here

最佳答案

在这种情况下,您可以尝试使用全局静态引用技术。

在 Application 类(一个扩展 Android Application 类的类)中声明您的 subview 。

public class AppController extends Application{
  public static final String LOG_TAG = ApplicationController.class
        .getSimpleName();

  // Application Instance
  private static ApplicationController applicationController = null;

  public static ListView childview;
  public static ChildAdapter childAdapter;

   @Override
   public void onCreate() {
    super.onCreate();
    applicationController = this;
   }
}

现在在你的任何 fragment 中假设 fragment A,检查 childFragment 的全局对象是否为 null,如果它的 null 像其他 chilfragments 一样正常初始化它,因为它的引用是全局的 AppController 中的变量现在包含 childfragment 的实例。

现在在 Fragment B 中检查全局引用是否为 null,因为你在 Fragment A 中初始化它你不会得到 null,现在像普通的 childfragments 一样将 childFragment 附加到 Fragment B

关于android - 如何在 viewpager 的所有 fragment 中获取相同的子 fragment (具有 recyclerview)实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41820213/

相关文章:

java - 从 ViewPager fragment 刷新 Activity

java - 将 fragment 添加到 xml 会使我的应用程序崩溃 - 如何解决这个问题?

java - Android:插入 fragment 时出错

android - 使用 RecyclerView 时未显示 BottomSheet

android - ItemTouchHelper - 在第一条跳线后强制放下

android - 扩展 ViewPager 的触摸区域

安卓 GPS 小部件

java - 另一个线程的监听器

android - fragment 事务中 2 个 View 的动画

android - GridView 在 Android 中究竟是如何回收/重用 View 的?