简体   繁体   中英

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.

However, I need to be able to initialize some variables in TheParent even though I am instantiating TheChild, so what I tried was:

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?

Static methods, like new instance in TheParent are "class" methods. Therefore, instead of calling super.newInstance, you should be calling TheParent.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". 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 ()".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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