【问题标题】:How to get same childfragments(having recyclerview) instance in all the fragments of viewpager?如何在viewpager的所有片段中获取相同的childfragments(具有recyclerview)实例?
【发布时间】:2017-01-24 04:50:14
【问题描述】:

我陷入了这样一种情况,即我有包含项目数据的 recyclerview,我需要在 viewpager 的所有片段(三个)中获取相同的实例以对同一个 recyclerview 进行操作。

我做了什么:

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

请帮助我克服这种情况或建议任何其他方式在所有 3 个片段中使用 common recyclerlist。我已经搜索了 stackoverflow,但没有任何帮助。

这是了解情况的图片:

【问题讨论】:

  • 请显示一些代码来说明您尝试过的内容。同时展示一些截图或模型来展示你的布局。
  • @Code-Apprentice 请查看图片以了解情况。代码很简单,一个tablayout在viewpager中有3个fragment,每个都需要有共同的子fragment用于recyclerview
  • 为什么子片段必须都是同一个实例?你可以创建同一个类的多个实例吗?
  • @Code-Apprentice 我需要所有三个片段之间的通用列表。目前,我在活动中使用静态列表并从所有三个实例中操作相同的列表,但这使我的 UI 变得笨重并且标签滑动太慢。我正在考虑想办法为所有 3 个选项卡使用 listFragment 的单个实例
  • “更好的方法”是什么意思?你还在谈论效率吗?从设计的角度来看,我将拥有一个共享的数据源,而不是共享一个片段的单个实例。但是,从效率的角度来看,您必须在尝试优化之前测量您的代码是否存在瓶颈。

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


【解决方案1】:

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

在Application类(继承Android的Application类的类)中声明你的childview。

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 像其他 chilfragment 一样正常初始化它,因为它的引用是全局的,AppController 中的变量现在包含 childfragment 的实例。

现在在 Fragment B 中检查全局引用是否为 null,因为您在 Fragment A 中对其进行了初始化,所以您不会得到 null,现在像普通 childfragments 一样将 childFragment 附加到 Fragment B

【讨论】:

  • 我会试一试并回复给你
猜你喜欢
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
相关资源
最近更新 更多