1

我试图提出一个评级类型的问题,我想在单选按钮中设置值..但我无法计算选中按钮的总和..这是我的代码..

公共类 MainActivity 扩展 Activity {

public RadioButton r0,r1,r2,r3,r4,r5,r6,r7,r8,r9;
public RadioGroup rg1,rg2;
public TextView tv1;
public Button btn1;
public static int a,b,c,d,e,a1,b1,c1,d1,e1,total;


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


    r0 = (RadioButton)findViewById(R.id.radio0);
    r1 = (RadioButton)findViewById(R.id.radio1);
    r2 = (RadioButton)findViewById(R.id.radio2);
    r3 = (RadioButton)findViewById(R.id.radio3);
    r4 = (RadioButton)findViewById(R.id.radio4);
    r5 = (RadioButton)findViewById(R.id.radio5);
    r6 = (RadioButton)findViewById(R.id.radio6);
    r7 = (RadioButton)findViewById(R.id.radio7);
    r8 = (RadioButton)findViewById(R.id.radio8);
    r9 = (RadioButton)findViewById(R.id.radio9);


    btn1 = (Button)findViewById(R.id.button1);

    tv1 = (TextView)findViewById(R.id.textView7);

    rg1 = (RadioGroup)findViewById(R.id.radioGroup1);
    rg2 = (RadioGroup)findViewById(R.id.radioGroup2);



    btn1.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {


    switch(rg1.getCheckedRadioButtonId()){

    case R.id.radio0:
        if (r0.isChecked()){
            a =1;



        }
            break;
    case R.id.radio1:
        if (r1.isChecked()){
            b = 2;


        }
            break;
    case R.id.radio2:
        if (r2.isChecked()){
            c = 3;


        }
            break;
    case R.id.radio3:
        if (r3.isChecked()){
            d = 4;

        }
            break;
    case R.id.radio4:
        if (r4.isChecked()){
            e = 5;


        }
            break;
    }

    //no. 2
    switch(rg2.getCheckedRadioButtonId()){

    case R.id.radio5:
        if (r5.isChecked()){
            a1=1;

        }
            break;
    case R.id.radio6:
        if (r6.isChecked()){
            b1 = 2;


        }
            break;
    case R.id.radio7:
        if (r7.isChecked()){
            c1 = 3;

        }
            break;
    case R.id.radio8:
        if (r8.isChecked()){
            d1 = 4;

        }
            break;
    case R.id.radio9:
        if (r9.isChecked()){
            e1 = 5;

        }
            break;
    }

//我想得到两个选中的单选按钮并输出结果..请帮助我

    total = rg1.getCheckedRadioButtonId() + rg2.getCheckedRadioButtonId();

    tv1.setText("result: "+total);



}


    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

4

1 回答 1

0

看这个:

total = rg1.getCheckedRadioButtonId() + rg2.getCheckedRadioButtonId();

您正在尝试添加 RadioButtonId,它们是 radio1、radio2 等。

可能有很多方法可以做到这一点,但我想我会创建一个 sum 变量,将所选数字添加到其中。

case R.id.radio5:
    if (r5.isChecked()){
        //a1=1;
        sum += 1;
    }

最后

tv1.setText("result: "+ sum);

您每次都需要重置总和,这样它就不会一直添加到以前的总和中。

于 2012-12-02T17:58:24.417 回答