RadioButton(單選按鈕)在Androi發中應用的非常廣泛,比如一些選擇項的時候,會用到單選按鈕。它是一種單個圓形單選框雙狀態的按鈕,可以選擇或不選擇。在RadioButton沒有被選中時,用戶能夠按下或點擊來選中它。但是,與復選框相反,用戶一旦選中就不能夠取消選中。
實現RadioButton由兩部分組成,也就是RadioButton和RadioGroup配合使用.RadioGroup是單選組合框,可以容納多個RadioButton的容器.在沒有RadioGroup的情況下,RadioButton可以全部都選中;當多個RadioButton被RadioGroup包含的情況下,RadioButton隻可以選擇一個。並用setOnCheckedChangeListener來對單選按鈕進行監聽
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/sex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sex" />
<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/female"
android:text="@string/female"
></RadioButton>
<RadioButton
android:id="@+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/male"
android:checked="true"
></RadioButton>
</RadioGroup>
</LinearLayout>
RadioGroupActivity.java
通過控件的ID來得到代表控件的對象
然後為RadioGroup設置監聽器
package Android.Activity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class RadioGroupActivity extends Activity {
/** Called when the activity is first created. */
private RadioButton maleButton = null;
private RadioButton femaleButton = null;
private RadioGroup radiogroup =null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//通過控件的ID來得到代表控件的對象
maleButton = (RadioButton)findViewById(R.id.male);
femaleButton = (RadioButton)findViewById(R.id.female);
radiogroup = (RadioGroup)findViewById(R.id.radiogroup);
//為RadioGroup設置監聽器,需要註意的是,這裡的監聽器和Button控件的監聽器有所不同
radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if(femaleButton.getId() == checkedId){
Toast.makeText(RadioGroupActivity.this, "female", Toast.LENGTH_SHORT).show();
}
else if(maleButton.getId() == checkedId){
Toast.makeText(RadioGroupActivity.this, "male", Toast.LENGTH_SHORT).show();
}
}
});
}
}
摘自 落日小屋