如何在 switch 语句上实现验证?

How to implement validation onto a switch statement?

简单的 switch 语句,将下一个按钮作为最终案例。我想要它,所以用户在继续之前必须 select 切换语句中的图像。我不知道如何写一些东西来阻止他们,用户只需单击下一个按钮并移动到下一个 activity,而无需从 switch 语句中创建 selection。下面的代码。

    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);
            }
    }
}

简而言之,您需要做的就是在用户选择一个选项后翻转一个标志。如果该标志未翻转,则让下一个按钮的操作不执行任何操作。

如果按钮不执行任何操作,则将按钮变灰或以其他方式将其显示为禁用也是一个好主意,但我不会解释如何执行此操作,因为它超出了这个问题的范围。

祝你好运!

您可以从 switch 语句外部启动活动 随便写

按钮按钮下一步。 = findViewById..

buttonNext.SetOnClickListener...