Reputation: 768
I know with Fragments we cannot use its constructor because the system needs the empty one. So to pass data we need to use a static method and bundles like
public static A newInstance(int myInt){
A myA = new A();
Bundle args = new Bundle();
args.putInt("myInt", someInt);
myA.setArguments(args);
return myA;
}
Okay so far so good.
But what if I want to generify this?
public abstract class C{
private int myInt;
//Here I cannot use the newInstance because I cannot create an instance of an abstract class
}
The outcome should be that I have constructs like this
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
}
Both A and B need myInt
so I would like to have a newInstance method provided by the superclass that I can call and the outcome should be a instance of A or B. How to do this/Is this possible?
Upvotes: 0
Views: 196
Reputation: 6277
It is not mandatory to have a static method in fragment class to create it's instance. You can create it from outside as well. A Parent class usually is not supposed to know about its child classes.
Retrieve the Bundle arguments from the base class C
and set myInt
there.
A
and B
will get the access. Make sure myInt
has a protected
access modifier.
Upvotes: 1
Reputation: 8345
In class C
you can store the instance variable myInt
, and then override onCreate()
and in that extract the myInt
value from the arguments bundle.
When creating a new A
(A.getInstance(...)
), you need to put the myInt
value in the argument bundle. You need to do the same thing when creating a new B
. To avoid copy-pasting code, you can add a helper method in C
called (for example) createArgumentsBundle(myInt)
, that creates a new bundle with myInt
in it and then send back the bundle.
Upvotes: 1