简体   繁体   English

创建扩展父片段的子片段时调用 newInstance()

[英]Calling newInstance() when creating a child fragment extending a parent fragment

I have a parent DialogFragment called TheParent and a child Fragment called TheChild which extends TheParent.我有一个名为 TheParent 的父 DialogFragment 和一个名为 TheChild 的子 Fragment,它扩展了 TheParent。

However, I need to be able to initialize some variables in TheParent even though I am instantiating TheChild, so what I tried was:但是,即使我正在实例化 TheChild,我也需要能够在 TheParent 中初始化一些变量,所以我尝试的是:

In the parent在父

public static TheParent newInstance(int myInt) {
    Bundle args = new Bundle();
    TheParent fragment = new TheParent();
    args.putInt(ARGUMENT_MYINT, myInt);
    fragment.setArguments(args);
    return fragment;
}

and then in the child:然后在孩子中:

public static TheChild newInstance(int myInt) {
    return super.newInstance(myInt);
}

However it does not like me doing this because of the static context.但是,由于静态上下文,它不喜欢我这样做。

What is the correct way to call newInstance() on TheChild and have it invoke newInstance() of the parent?在 TheChild 上调用 newInstance() 并让它调用父级的 newInstance() 的正确方法是什么?

Static methods, like new instance in TheParent are "class" methods.静态方法,如 TheParent 中的 new 实例是“类”方法。 Therefore, instead of calling super.newInstance, you should be calling TheParent.newInstance (...).因此,您应该调用 TheParent.newInstance (...),而不是调用 super.newInstance。 Just remember the way to call static methods is by using the class name.请记住,调用静态方法的方法是使用类名。 Hope it helps.希望能帮助到你。 All that said, the newInstance method in TheChild has a return value of type "TheChild".尽管如此,TheChild 中的 newInstance 方法具有“TheChild”类型的返回值。 This means that returning a "TheParent" instance would be impossible, it would result in a compile time error that you will see as soon as you change the code in TheChild from: "return super.newInstance()" to "TheParent.newInstance ()".这意味着返回“TheParent”实例是不可能的,它会导致编译时错误,一旦您将 TheChild 中的代码从“return super.newInstance()”更改为“TheParent.newInstance ( )”。

This is what I did to keep from having to repeat all the logic in the child class:这是我为了避免重复子类中的所有逻辑而所做的:

public static TheChild newInstance(int myInt) {
    TheChild fragment = new TheChild();
    fragment.setArguments(TheParent.newInstance(myInt).getArguments());
    return fragment;
}

Of course, this solution creates a second instance of TheParent momentarily.当然,此解决方案会立即创建TheParent的第二个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM