RadioGroup與RadioButton 控件
首先需要在佈局文件中設置RadioGroup的屬性,然後在該RadioGroup中添加RadioButton的屬性。這也可以認為,RadioGroup是RadioButton的一個容器,首先建立容器,然後在容器中添加物體。
代碼片段如下:
<RadioGroup
android:id="@+id/gender"//設置id
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"//設置RadioGroup中RadioButton的排列方向
>
<RadioButton
android:id="@+id/male"//設置id
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/male"
/>
<RadioButton
android:id="@+id/female"//設置id
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/female"
/>
</RadioGroup>
佈局文件寫完之後,在所在Activity類中添加RadioGroup和RadioButton的對象。
因為是單選的,所以這個控件的事件需要設置在RadioGroup上,可以使用RadioGroup的setOnCheckedChangeListener的方法添加RadioGroup的OnCheckedChangeListener的監聽器,需要Override其中的onCheckedChanged(RadioGroup group, int checkedId)方法,參數很明顯,是所在group對象和所改變的RadioButton的id,在方法內部可以對RadioGroup以及RadioButton進行操作。
代碼片段如下:
RadioGroup genderGroup = (RadioGroup)findViewById(R.id.gender);
RadioButton maleButton = (RadioButton)findViewById(R.id.male);
maleButton.setChecked(true);//默認選擇男
RadioButton femaleButton = (RadioButton)findViewById(R.id.female);
genderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if(femaleButton.getId()==checkedId){
Toast.makeText(ControlDemo2Activity.this, "Female", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ControlDemo2Activity.this, "Male", Toast.LENGTH_SHORT).show();
}
}
});
運行效果:
CheckBox控件
首先要在佈局文件中定義CheckBox的樣式id等信息,每一個CheckBox都需要定義。
代碼片段如下:
<CheckBox
android:id="@+id/apple"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/apple"
/>
<CheckBox
android:id="@+id/orange"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/orange"
/>
<CheckBox
android:id="@+id/mango"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/mango"
/>
定義完CheckBox的之後,在Activity中創建CheckBox的對象,每個CheckBox上都可以設置監聽器,可以使用CheckBox的setOnCheckedChangeListener的方法添加CompoundButton的OnCheckedChangeListener的監聽器,需要Override其中的onCheckedChanged(CompoundButton arg0, boolean arg1),第一個參數是你所點擊的CheckBox的對象,第二個參數是該對象是否被選中的boolean值,在方法中可以自己定義一些功能效果。
代碼片段如下:
CheckBox appleCheck = (CheckBox)findViewById(R.id.apple);
appleCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
if(arg1==true)//當該Checkbox被按下
Toast.makeText(ControlDemo2Activity.this, "Apple Checked", Toast.LENGTH_SHORT).show();
else
Toast.makeText(ControlDemo2Activity.this, "Apple Unchecked", Toast.LENGTH_SHORT).show();
}
});
運行效果:
以上的兩種控件的樣式是可以在佈局文件或者對象中可以設置。
附件為示例代碼,僅供參考。嘎嘎~
本文出自 “戰神殿” 博客