1. 程式人生 > 實用技巧 >瞭解Android_05之RadioButton

瞭解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();
            }
        });
    }
}