为所选的每个单选按钮分配点

时间:2017-08-17 12:24:32

标签: android radio-button

我目前正在开发一个基于问卷调查的应用程序,其中有选项。我需要为每个单选按钮分配数值,这样当选择其中一个时,它将给出一定数量的点,然后用于产生累积量。我需要帮助编写java来执行此操作。任何帮助将不胜感激。谢谢!

int score = 0;
public TextView tv;

public void onRadioButtonClicked(View view) {
    boolean checked = ((RadioButton) view).isChecked();

    switch (view.getID()) {
        case R.id.radioButton1:
            if(checked)
                score +=1;
            break;

        case R.id.radioButton2:
            if(checked)
                score +=1;
            break;

        case R.id.radioButton3:
            if(checked)
                score +=3;
            break;
    }
}

public void updateScore(int score) {
    tv = (TextView)findViewById(R.id.textview1);
    tv.setText(" " + score);
}
我在XML中用<&#34; 0&#34;编写了一个textview。和文本ID @+id/textview1

问题是,即使选择了任何单选按钮,分数仍为0

1 个答案:

答案 0 :(得分:0)

对您的代码进行以下更改

public TextView tv;
int score = 0;

public void onRadioButtonClicked(View view) {
    boolean checked = ((RadioButton) view).isChecked();

    switch (view.getId()) {   
        case R.id.radioButton1:
            if (checked) {
                score += 1;
            }
            break;

        case R.id.radioButton2:
            if(checked)
                score +=1;
            break;

        case R.id.radioButton3:
            if(checked)
                score +=3;
            break;
    }
    updateScore(score);  // <- Added this line here
}

public void updateScore(int score) {
    // Don't initialise your view here. Take it to onCreate()
    tv.setText(" " + score);
}

修改

单选按钮的XML是否与我在这里的类似?

<RadioButton
    android:id="@+id/radioButton1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="asas"
    android:onClick="onRadioButtonClicked"/>

确保已将android:onClick="onRadioButtonClicked"属性添加到每个单选按钮