功能
從多種選擇中選擇一個,需要單選按鈕,經典場景是選擇性別男、女。
顯示
單選按鈕需要放到單選按鈕組RadioGroup中,每組中只有一個元素可以被選中。RadioGroup常用屬性有:
- check,設置選中按鈕的資源編號
- getCheckedRadioButtonId,獲取選中按鈕的資源編號
實例代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="4dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="請選擇性別"/>
<RadioGroup
android:id="@+id/radioGroupSex"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"
android:checked="true"/>
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"/>
</RadioGroup>
<Button
android:id="@+id/buttonOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="確認"/>
</LinearLayout>
效果:
獲取選中項
點擊確認按鈕後,獲取選中項,並彈窗提示,代碼如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//獲取按鈕
Button buttonOk = findViewById(R.id.buttonOk);
//設置按鈕點擊監聽器
buttonOk.setOnClickListener(new MyOnClickListener());
}
//定義按鈕點擊監聽器
class MyOnClickListener implements View.OnClickListener {
//按鈕點擊
@Override
public void onClick(View view) {
if (view.getId() == R.id.buttonOk) {//被點擊的是確認按鈕
//獲取選中項
RadioGroup radioGroup = findViewById(R.id.radioGroupSex);
String sex = "";
if (radioGroup.getCheckedRadioButtonId() == R.id.radioMale) {
sex = "男";
} else {
sex = "女";
}
//顯示提示框
Toast.makeText(MainActivity.this, "你選擇了:" + sex, Toast.LENGTH_SHORT).show();
}
}
}
}
效果:
監聽選中項變化
當選中項發生變化時,可以監聽該變化,代碼如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup radioGroup = findViewById(R.id.radioGroupSex);
//設置監聽器
radioGroup.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
}
class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener{
//用戶點擊單選按鈕觸發
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if(i==R.id.radioMale){
Toast.makeText(MainActivity.this, "你選擇了:男", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "你選擇了:女" , Toast.LENGTH_SHORT).show();
}
}
}
}
注意當選中項變化時纔會觸發!