Reputation: 35
I want to make small game with some levels where user make input based on what he see on the screen and if it is valid - level is passed.
I have LevelActivity which manages different fragments of levels. I wanted to make LevelFragment as abstruct class and then extend it with different child Fragments (Levels) such as SimplestLevelFragment.
All levels have some common arguments and i don`t know how to pass them to superclass?
Provided code:
LevelFragment.java
public abstract class LevelModelFragment extends Fragment {
protected boolean completed;
private int id;
private String name;
private String[] hints;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return provideFragmentView(inflater, container, savedInstanceState);
}
protected abstract View provideFragmentView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState);
public abstract boolean checkCompletion();
public abstract void handleInput(String input);}
SimplestLevelFragment.java
public class SimplestLevelFragment extends LevelModelFragment {
private final static int id = 1;
private final static String name = "The simplest level I have ever seen";
private final static String[] hints = {"Enter the name of program"};
@Override
protected View provideFragmentView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.simpleLevelLayout,parent,false);
//Now specific components here (you can initialize Buttons etc)
return view;
}
@Override
public boolean checkCompletion() {
return this.completed;
}
@Override
public void handleInput(String input) {
if(input == "Secret Path"){
this.completed = true;
}
}}
Maybe I should use another architecture approach?
Upvotes: 0
Views: 480
Reputation: 5241
When you init child Fragment
you should put common arguments into Bundle
and call setArguments
. In super Fragment
inside the method onCreate
you can get it.
Fragment child = new SimplestLevelFragment();
Bundle data = new Bundle();
// put common value to data
child.setArguments(data);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getArguments();
// get common value you already pass
}
Upvotes: 1