Android學習手冊-RadioGroup, RadioButton1

完成圖
  1. 介面布局檔拉RadioGroup元件,包覆RadioButton元件。RadioGroup中checkedButton屬性是設置在未點選時預設為點選哪一個。
<RadioGroup
android:id="@+id/radGrp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkedButton="@id/radBtnMale">

<RadioButton
android:id="@+id/radBtnMale"
android:textSize="25sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />

<RadioButton
android:id="@+id/radBtnFemale"
android:textSize="25sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>

2. 在MainActivity.java中建立mradGrp元件,連結至radGrp。

當"建議"按鈕被點下時,看是哪個RadioButton被點到,使用switch case寫,寫在按鈕的setOnClickListner裡面。

getCheckedRadioButtonId()檢查哪個RadioButton被點到。

mbtn.setOnClickListener(v -> {
int age = Integer.parseInt(medtAge.getText().toString());
res = "";

switch (mradGrp.getCheckedRadioButtonId()){
case R.id.radBtnMale:
if(age < 28){
res += "還不急著結婚";
}
else if(age > 33){
res += "趕快找個對象";
}
else{
res += "可以再飄泊一下";
}
break;
case R.id.radBtnFemale:
if(age < 25){
res += "還不急著結婚";
}
else if(age > 30){
res += "趕快找個對象";
}
else{
res += "可以再飄泊一下";
}
}

mtxtDisplay.setText(res);
});

完整Mainactivity.java和介面布局檔請至下面網站中搜尋:

RadioGroup開頭的java及xml檔案

RadioGroup, RadioButton第二集

https://andreea337.medium.com/android-studio%E5%AD%B8%E7%BF%92%E6%89%8B%E5%86%8A-radiogroup-radiobutton2-dc3f47dc5a3f

--

--

IM rookie

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store