Andriod控件之RadioButton

RadioButton

RadioButton是android控件中的一种单选按钮,默认是圆形的,不过你也可以自定义。

<RadioButton
        android:id="@+id/radio_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hobby"
        android:textSize="20sp"/>

当你要自定义按钮的形状的时候,你需要把button属性设置为null

<ButtonRadio
           android:button="@null"
           android: background="你自定义的形状shape"/>

RadioGroup

一个RadioGroup标签可以包含多个RadioButton控件,不过只能选中一个。

 <RadioGroup
        android:id="@+id/rg_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="30dp">
        <RadioButton
        android:id="@+id/radio_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Male"
        android:textSize="20sp"
            android:checked="true"
        />
        <RadioButton
            android:id="@+id/radio_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Female"
            android:textSize="20sp"
            />
    </RadioGroup>

其中checked属性是默认选中。

获取按钮信息

        radioGroup2 = findViewById(R.id.rg_2);
        radioButton4 = findViewById(R.id.radio_4);
        radioButton5 = findViewById(R.id.radio_5);

        radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                String text = null;
                if(radioButton4.getId() == i) {
                    text = radioButton4.getText().toString();
                } else {
                    text = radioButton5.getText().toString();
                }
                Toast.makeText(RadioButtonActivity.this, text, Toast.LENGTH_SHORT).show();
            }
        });

setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()):监听按钮组中是否有按钮被按下。
public void onCheckedChanged(RadioGroup radioGroup, int i):当有按钮选中时检测按钮的变化,其中第二个参数i记录的是选中的按钮的id属性;
radioButton4.getId(): 获取按钮的id值;
radioButton5.getText().toString():获取按钮的信息。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值