I am making an application that involves create/retrieve/update/delete operations.
So for the add and edit method I want to re-use core components that are the same in both functions. So I made a shared abstract class and then my add and edit classes extend the shared so they each have the same core but can still have differences.
I instantiate these objects/Fragments by using the newInstance method, which is where I usually pass in arguments, set them into the Bundle, and then read them back in the onCreateView methods.
However I need to be able to pull in arguments to the shared class, but I can't because it's abstract, and when I instantiate the objects, I am instantiating Edit and Add objects, which means only the child classes can have arguments.
What's the accepted practice for getting around this?
public abstract class SharedStuffDialogFragment extends DialogFragment {
protected MyObject mMyObject; //I'd like to be able to init. this
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.shared_layout, container, false);
//do a bunch of other stuff here, sharable attributes
initOtherThings(savedInstanceState);
return contentView;
}
protected abstract void initOtherThings(Bundle savedInstanceState);
}
And then for example, the add class:
public class AddDialogFragment extends SharedStuffDialogFragment {
private static final String ARGUMENT_OBJECT = "argument_object";
private MyObject mMyObject;
public static AddDialogFragment newInstance(MyObject object) {
Bundle args = new Bundle();
args.putParcelable(ARGUMENT_OBJECT, object); //would really rather set this to shared
AddDialogFragment fragment = new AddDialogFragment();
fragment.setArguments(args);
return fragment;
}
@Override
protected void initOtherThings(Bundle savedInstanceState) {
mMyObject = getArguments().getParcelable(ARGUMENT_OBJECT);
//do stuff unique to add operations
}
}
Aucun commentaire:
Enregistrer un commentaire