最后一个简单的switch
语句带有下一个按钮。我想要它,因此用户必须先在switch语句中选择一个图像,然后再继续。我不知道如何写一些东西来阻止他们,用户只需单击下一个按钮并转到下一个活动,而无需从switch语句中进行选择。下面的代码。
public void onClick(View v) {
SharedPreferences.Editor editorWorkout = workoutPref.edit();
// get the constraint layout from its ID.
ConstraintLayout mConstraintLayout = getView().findViewById(R.id.FragmentWorkoutMood1);
switch (v.getId()) {
case R.id.excitedFace:
mConstraintLayout.setBackgroundResource(R.mipmap.background_clouds_excited);
editorWorkout.putInt("excitedkey", EXCITED.getId());
editorWorkout.commit();
break;
case R.id.happyFace:
mConstraintLayout.setBackgroundResource(R.mipmap.background_clouds_happy);
editorWorkout.putInt("happykey", HAPPY.getId());
editorWorkout.commit();
break;
case R.id.fineFace:
mConstraintLayout.setBackgroundResource(R.mipmap.background_clouds_fine);
editorWorkout.putInt("finekey", FINE.getId());
editorWorkout.commit();
break;
case R.id.nextBtnMoodPage:
Intent intent = new Intent(getActivity(), WorkoutAutomaticThoughtActivity.class);
startActivity(intent);
}
最佳答案
您需要禁用nextBtnMoodPage
所执行的操作,直到用户选择了其他任何选项。使用简单的布尔值执行此操作。见下文:
// Inside the class itself
private boolean hasSelected = false;
public void onClick(View v) {
SharedPreferences.Editor editorWorkout = workoutPref.edit();
// get the constraint layout from its ID.
ConstraintLayout mConstraintLayout = getView().findViewById(R.id.FragmentWorkoutMood1);
switch (v.getId()) {
case R.id.excitedFace:
mConstraintLayout.setBackgroundResource(R.mipmap.background_clouds_excited);
editorWorkout.putInt("excitedkey", EXCITED.getId());
editorWorkout.commit();
hasSelected = true;
break;
case R.id.happyFace:
mConstraintLayout.setBackgroundResource(R.mipmap.background_clouds_happy);
editorWorkout.putInt("happykey", HAPPY.getId());
editorWorkout.commit();
hasSelected = true;
break;
case R.id.fineFace:
mConstraintLayout.setBackgroundResource(R.mipmap.background_clouds_fine);
editorWorkout.putInt("finekey", FINE.getId());
editorWorkout.commit();
hasSelected = true;
break;
case R.id.nextBtnMoodPage:
if(hasSelected){
Intent intent = new Intent(getActivity(), WorkoutAutomaticThoughtActivity.class);
startActivity(intent);
}
}
}
简而言之,您需要做的就是一旦用户选择了一个选项,就翻转一个标志。如果该标志未翻转,则使下一个按钮的操作无效。
如果不执行任何操作,则将按钮变灰或将其显示为禁用也是一个好主意,但是由于该问题超出了我的范围,因此我不会解释如何执行此操作。
祝好运!
关于java - 如何在switch语句上实现验证?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56245987/