第七课 RadioGroup和RadioButton的用法

1.RadioButton一般都是分组使用,即先创建一个组RadioGroup(是一个方框),然后将RadioButton在方框中排列,那么方框中的RadioButton就属于同一个组,同时要给RadioGroup添加一个ID.在以后的控制中只需给这个组添加一个监听器即可。

2.如何给组添加监听器,并找出是组中的哪一个成员按下

public class MainActivity extends AppCompatActivity {
    TextView tx;
    RadioGroup G_name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tx = (TextView)findViewById(R.id.textView2);
        G_name = (RadioGroup)findViewById(R.id.RadioGroup1);
       //创建并实现监听器(此处和之前创建的监听器方法不同,这一次在创建的时候就实现监听整个过程都是在onCreate中完成)
        G_name.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                //获取变更后的选中项的ID
                int radioButtonId = arg0.getCheckedRadioButtonId();//获得按下单选框的ID,并保存在radioButtonId
                //根据ID获取RadioButton的实例
                RadioButton rb = (RadioButton)findViewById(radioButtonId);//根据ID将RB和单选框绑定在一起
                //更新文本内容,以符合选中项
                tx.setText("您的名字是:" + rb.getText());//获取单选框的文字,并在TextView中显示
            }
        });//监听器到此结束

     //   ImageSpan span = new ImageSpan(this, R.mipmap.xiaogou);
      //  SpannableString spanStr = new SpannableString("我是小狗 ");
       // spanStr.setSpan(span, spanStr.length()-1, spanStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
      //  tx.setText(spanStr);
    }

}

 

posted @ 2016-07-11 23:59  qq921201008  阅读(5367)  评论(0编辑  收藏  举报