RadioButton控件

RadioGroup

RadioGroup常用于将若干个RadioButton当做一组来处理;
RadioGroup是LinearLayout的子类,也属于容器类型。

一、RadioButton的使用

如果想要互斥效果,必须在RadioButton加上唯一的id值,且放在同一个RadioGroup当中

<RadioGroup
     android:id="@+id/rgGenger"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">
     <RadioButton
          android:id="@+id/rbFemale"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="女"
          android:checked="true"/>
     <RadioButton
          android:id="@+id/rbMale"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="男"/>
</RadioGroup>
效果图
RadioButton.png
二、获得RadioButton取得的值

通过RadioGroup的getCheckedRadioButtonId()方法可以找到选中的RadioButton

public void onClick(View view){
    RadioGroup  group= (RadioGroup) findViewById(R.id.rgGenger);
    int id=group.getCheckedRadioButtonId();
    RadioButton radio= (RadioButton) findViewById(id);
    String str=radio.getText().toString();
    Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
}

通过RadioGroup的RadioGroup.onCheckedChangeListener接口

private void initView(){
    RadioGroup group= (RadioGroup) findViewById(R.id.rgGenger);
    group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i){
            case R.id.rbFemale:
                Toast.makeText(RadioActivity.this,"性别女",Toast.LENGTH_SHORT).show();
                break;
            case R.id.rbMale:
                Toast.makeText(RadioActivity.this,"性别男",Toast.LENGTH_LONG).show();
                break;
                  }    
                                                                               }
});
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 基本UI Zealer、CSDN、github StormZhang、 张弘扬(Hyman):http:/...
    征程_Journey阅读 14,163评论 0 4
  • 在实际的项目中,我们经常都是RadioButton和RadioGroup一起配合使用。RadioGroup是单选组...
    fodroid阅读 13,802评论 12 99
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,660评论 25 709
  • 我不知道别人的脸是不是和我一样,一个小时不去管它,就会浸出厚厚的油脂,手指一抹,像抹一口刚炒完菜的锅。所以,什么都...
    瞿桂林阅读 25评论 0 0
  • 今天和以往的每一天没有什么不同,早上在手机闹声中醒来,慢慢的蠕动着爬起,穿衣发愣、起身洗漱!半个小时的化妆,香...
    欢乐小马阅读 2,773评论 0 0