如何将参数传递给超类片段

How to pass arguments to superclass fragment

我知道对于 Fragments 我们不能使用它的构造函数,因为系统需要空的。所以要传递数据,我们需要使用静态方法和像

这样的包
public static A newInstance(int myInt){
    A myA = new A();

    Bundle args = new Bundle();
    args.putInt("myInt", someInt);
    myA.setArguments(args);

    return myA;
}

到目前为止还不错。

但是如果我想泛化这个怎么办?

public abstract class C{
    private int myInt;

    //Here I cannot use the newInstance because I cannot create an instance of an abstract class
}

结果应该是我有这样的结构

public class A extends C{
   //Some stuff that needs myInt which is stored in superclass because every subclass fragment needs it
}

public class B extends C{
   //Some completly other stuff that also needs myInt
}

A 和 B 都需要 myInt 所以我想要一个由超类提供的 newInstance 方法,我可以调用它并且结果应该是 A 或 B 的实例。怎么做 this/Is 这可能吗?

在片段 class 中创建实例的静态方法不是强制性的。您也可以从外部创建它。 Parent class 通常不应该知道它的 child classes.

从基础 class C 中检索 Bundle 参数并在那里设置 myInt

AB 将获得访问权限。确保 myInt 具有 protected 访问修饰符。

在 class C 中,您可以存储实例变量 myInt,然后覆盖 onCreate() 并从参数中提取 myInt 值捆绑。

创建新的AA.getInstance(...))时,需要将myInt值放入参数包中。创建新 B 时,您需要做同样的事情。为避免复制粘贴代码,您可以在 C 中添加一个名为(例如)createArgumentsBundle(myInt) 的辅助方法,它会创建一个包含 myInt 的新包,然后将包发回。