了解Android_05之RadioButton

一、RadioButton是什么?

  字面翻译即单选按钮。

二、RadioButton样式:

<RadioGroup
        android:id="@+id/rg1"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:orientation="horizontal"
    >
        <RadioButton
            android:id="@+id/rb1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="男"
            android:textSize="34sp"
            android:button="@null"
            android:checked="true"
            android:background="@drawable/radio_button"
            android:layout_weight="1"
            android:gravity="center"
        />
        <RadioButton
            android:id="@+id/rb2"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="女"
            android:textSize="34sp"
            android:button="@null"
            android:background="@drawable/radio_button"
            android:layout_weight="1"
            android:gravity="center"
        />
    </RadioGroup>

分析:

 

 

 自定义样式xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape>
            <solid android:color="#E6941A"/>
            <corners android:radius="8dp"/>
        </shape>
    </item>
    <item android:state_checked="false">
        <shape>
            <stroke
                android:color="#E6941A"
                android:width="1dp"
            />
            <corners android:radius="8dp"/>
        </shape>
    </item>
</selector>

由于我这里使用的是真机调试,效果不好展示,效果为按钮被选中时填充一个橘色,未选中时为描边的样式:

 

 

 三、选中时触发的事件:

public class MainActivity extends AppCompatActivity {
    private RadioGroup rg1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rg1 = findViewById(R.id.rg1);
        rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                RadioButton rb = radioGroup.findViewById(i); //通过单选按钮组来获取被选中的单选按钮
                Toast.makeText(MainActivity.this,rb.getText(),Toast.LENGTH_SHORT).show();
            }
        });
    }
}

 

posted @ 2020-10-23 21:47  曾经沧海难为水。  阅读(187)  评论(0编辑  收藏  举报