获得RadioButton的价值

时间:2017-10-19 17:28:37

标签: java android

如何将简单单选按钮测验的值输入到新的XML布局页面。我不确定发生了什么。当我点击按钮时,它会强行关闭。

TextView hasil;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btnSubmit = (Button) findViewById(R.id.submit);
    btnSubmit.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View view){
            int score = 0;
            if (((RadioButton)findViewById(R.id.radioButton1)).isChecked()) {score++;}
            if (((RadioButton)findViewById(R.id.radioButton8)).isChecked()) {score++;}
            if (((RadioButton)findViewById(R.id.radioButton11)).isChecked()) {score++;}
            if (((RadioButton) findViewById(R.id.radioButton16)).isChecked()){score++;}
            if (((RadioButton) findViewById(R.id.radioButton19)).isChecked()){score++;}
            if (((RadioButton) findViewById(R.id.radioButton24)).isChecked()){score++;}
            if (((RadioButton) findViewById(R.id.radioButton25)).isChecked()){score++;}
            if (((RadioButton) findViewById(R.id.radioButton29)).isChecked()){score++;}

            displayResult(score);
        }

    });
}

private void displayResult(int score) {
    String message = "You scored " + score;
    message += " out of 6";
    message += "\nWell done!";
    hasil.setText(message);
}

2 个答案:

答案 0 :(得分:1)

您似乎没有初始化hasil TextView。 通过将HASIL_ID替换为适当的ID,在OnCreate方法中添加以下行。

class MyClass(object):
    @staticmethod
    def recursive_function(input):
        # ...
        sth = MyClass.recursive_function(subinput)
        # ...
        return sth

答案 1 :(得分:1)

您应该添加logcat消息,以便人们知道导致您的应用崩溃的原因。

但是,如果您想知道选中哪个单选按钮,可以尝试以下代码。

int score=0;
RadioGroup rg = (RadioGroup)findViewById(R.id.YOUR_RADIO_GROUP_ID);
switch (rg.getCheckedRadioButtonId()) {
                case R.id.radioButton1:
                    score++;
                    break;
                case R.id.radioButton8:
                    score++;
                    break;
                case R.id.radioButton11:
                    score++;
                    break;
                case R.id.radioButton16:
                    score++;
                    break;
                case R.id.radioButton19:
                    score++;
                    break;
                case R.id.radioButton24:
                    score++;
                    break;
                case R.id.radioButton25:
                    score++;
                    break;
                case R.id.radioButton29:
                    score++;
                    break;
                default:
                    break;
            }

我假设您已将单选按钮放在收音机组中。