在Java中更改Switch语句中String的值

时间:2017-06-15 12:13:25

标签: java android radio-button switch-statement android-radiogroup

我试图在 Android 中的切换语句中更改String数据类型的值。并且该String在声明中的switch语句的同一方法中声明,当用户单击单选按钮时,我需要更改String 的值。

public void CreateQuestion(View view) {

    String questionType = new String();
    RadioGroup questionTypeRadioGroup = (RadioGroup) findViewById(R.id.questionTypeRadioGroup);
    questionTypeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            switch (checkedId) {
                case R.id.true_false:
                    questionType = "True/False";
                    break;

                case R.id.mcqs:
                    questionType = "MCQs";
                    break;
            }
        }
    });
}

1 个答案:

答案 0 :(得分:1)

你应该全局声明你的字符串

public class ExampleActivity extends AppCompatActivity {
    public String questionType;

    ....

    public void CreateQuestion(View view) {
         questionType = "";
         questionTypeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
         @Override
         public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
              switch (checkedId) {
                     case R.id.true_false:
                          questionType = "True/False";
                          break;

                      case R.id.mcqs:
                          questionType = "MCQs";
                          break;
                    }
                }
            });
        }

    ....

}