在程序中有一個 spinner5 ,我在 values folder 中創建了兩個字符串數組 name_array 和 type_array 。還有兩個 radio buttons: radiobtn1 和 radiobtn2 。
我想實現的是當每個單選按鈕被選中時改變 spinner5 的內容。
if (radiobtn1 被選中)
then
spinner5 從 name_array 中顯示內容
else If (radiobtn2 被選中)
then
spinner5 從 type_array 中顯示內容
如何實現這個功能呢?
在 xml中寫入下面的代碼
<RadioGroup
android:layout_toRightOf="@+id/txtpref"
android:layout_marginLeft="10sp"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:textColor="#000000"
android:text="Male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radiobutton1"/>
<RadioButton
android:textColor="#000000"
android:text="Female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radiobutton2"/>
</RadioGroup>
In Your Java file
RadioButton radiobutton1,radiobutton2;
String [] name_array,type_array;
String [] temparray;
temparray = (name_array or type_array) // use any which you want disaplay first and use temparray to pass your adapter
ArrayAdapter arrayAdapter =new ArrayAdapter<String>(Activity_Name.this,android.R.layout.simple_spinner_item, temparray);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
radiobutton1 = (RadioButton) findViewById(R.id.radiobutton1);
radiobutton2 = (RadioButton) findViewById(R.id.radiobutton2);
radiobutton1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
// you want spinner5 to display contents from name_array.
temparray = name_array;
your_adapter.notifyDataSetChanged();
}
}
});
radiobutton2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
// you want spinner5 to display contents from type_array.
temparray = type_array;
your_adapter.notifyDataSetChanged();
}
}
});