android 中使用radiogroup (老人学android)
访问量: 2648
参考: https://developer.android.com/guide/topics/ui/controls/radiobutton.html#HandlingEvents
1. 在xml文件中:
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/english_language" // id 很重要,用于在java中获得值
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="英语" // 这个就是radio 的值
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="@+id/chinese_language"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="汉语"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
注意: 这个RadioGroup必须放在某个 layout中,否则不会正常显示在页面上。
2. 在activity中,加上如下代码(这个代码会被自动调用):
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.chinese_language:
if (checked)
Log.d("==", "checked chinese"); // 在这里就可以做事情了。
break;
case R.id.english_language:
if (checked)
Log.d("==", "checked english");
break;
}
}
3. 就可以了。