Android Studio學習手冊-RadioGroup, RadioButton2

示意圖

點擊male與female兩個不同的按鈕,下面年齡的選項也會隨著不同。

接續Android學習手冊-RadioGroup, RadioButton1

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

  1. 在xml檔中將edtAge刪除,加入RadioGroup包覆三個RadioButton
  2. 刪除java檔中和edtAge有關的變數
  3. 在string.xml中加入下列幾行code
<string name="fage1">小於25歲</string>
<string name="fage2">25~30歲</string>
<string name="fage3">超過30歲</string>
<string name="mage1">小於28歲</string>
<string name="mage2">28~33歲</string>
<string name="mage3">超過33歲</string>
<string name="suggest1">還不急著結婚</string>
<string name="suggest2">可以再飄泊一下</string>
<string name="suggest3">趕快找個對象</string>

4. setOnCheckedChangeListener(RadioGroup)

基本格式

mradGrpGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {

}
});

當不同RadioButton被按下時,要呈現不同的東西,如下示範

mradGrpGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.radBtnMale){
mradBtnAge1.setText(getString(R.string.mage1));
mradBtnAge2.setText(getString(R.string.mage2));
mradBtnAge3.setText(getString(R.string.mage3));
}
else{
mradBtnAge1.setText(getString(R.string.fage1));
mradBtnAge1.setText(getString(R.string.fage2));
mradBtnAge3.setText(getString(R.string.fage3));
}
}
});

5. 設置當建議按鈕被按下時,要出現的建議,寫在btn.setOnClickListener中

switch (mradGrpAge.getCheckedRadioButtonId()){
case R.id.radBtnAge1:
res += getString(R.string.suggest1);
break;
case R.id.radBtnAge2:
res += getString(R.string.suggest2);
break;
case R.id.radBtnAge3:
res += getString(R.string.suggest3);
break;
}

完整程式碼請至以下網站連結搜尋RadioGroup2

https://github.com/andreea337/Android-Studio-Examples

--

--

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