本帖最後由 tonyh 於 2017-8-12 17:48 編輯
RadioButton 元件支援多選一的選取操作。
- package com.example.student.myapplication;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.widget.RadioButton;
- import android.widget.RadioGroup;
- import android.widget.TextView;
- public class MainActivity extends AppCompatActivity {
- private TextView tv2;
- private RadioButton rb1, rb2, rb3;
- private RadioGroup rg;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- tv2= (TextView) findViewById(R.id.textView2);
- rb1= (RadioButton) findViewById(R.id.radioButton1);
- rb2= (RadioButton) findViewById(R.id.radioButton2);
- rb3= (RadioButton) findViewById(R.id.radioButton3);
- rg= (RadioGroup) findViewById(R.id.radioGroup);
- rg.setOnCheckedChangeListener(myListener);
- }
- private RadioGroup.OnCheckedChangeListener myListener=new RadioGroup.OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(RadioGroup group, int checkedId) {
- RadioButton rb= (RadioButton) findViewById(checkedId);
- tv2.setText(rb.getText());
- // if(checkedId==R.id.radioButton1)
- // tv2.setText(rb1.getText());
- // if(checkedId==R.id.radioButton2)
- // tv2.setText(rb2.getText());
- // if(checkedId==R.id.radioButton3)
- // tv2.setText(rb3.getText());
- }
- };
- }
複製代碼 |