In an android app, I have an Activity that holds a Fragment.
The fragment has an "updateScore" function that updated the UI with the current score.
This function is called from the fragment and should also be invoked from an option menu that resides in the activity.
This can be achieved if I save the context as a static variable in the Fragment, but this is a bad practice. So what should I do instead?
MainActivity:
public class MainActivity extends AppCompatActivity {
public static int totalCorrect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
ExerciseFragment exerciseFragment = new ExerciseFragment();
fragmentTransaction.add(R.id.fragment_container, exerciseFragment);
fragmentTransaction.commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
int id = item.getItemId();
if (id == R.id.option_reset_score) {
totalCorrect = 0;
ExerciseFragment.updateScore();
}
}
}
ExerciseFragment:
public class ExerciseFragment extends Fragment {
private static View view; //bad practice
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_exercises, container, false);
ExerciseFragment.view = view;
updateScore();
return view;
}
public static void updateScore() {
TextView totalCorrectTextView = (TextView) view.findViewById(R.id.total_correct);
totalCorrectTextView.setText(MyApp.getAppContext().getString(R.string.correct) + ": " + String.valueOf(MainActivity.totalCorrect));
}
}