我要做的是,你有2个RadioButton,当你点击其中一个时,它会显示一个ListView1,当你点击另一个RadioButton时,它会显示一个ListView2
这是我在我的xml文件中得到的:
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:paddingRight="5dp"
android:text="Free Apps" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paid Apps" />
</RadioGroup>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/radioGroup1" >
</ListView>
这就是我的.java中的内容:
private void populateListView() {
// Create list of items
String[] items = {"Test", "Test 2", "Test 3"};
String[] items2 = {"Bla", "Bla bla", "Bla bla bla"};
// Build Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.mainitem, items);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.mainitem, items2);
// Configure the list view
ListView list = (ListView) findViewById(R.id.listView1);
list.setAdapter(adapter);
}
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.radio0){
// Show items
}
if(checkedId == R.id.radio1){
// Show items2
}
}
public void onClick(View v) {
RadioGroup.clearCheck();
}
如果您还需要别的东西,请告诉我。谢谢!
答案 0 :(得分:0)
您只需要将populateListView方法中的内容添加到侦听器:
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.radio0){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.mainitem, items);
ListView list = (ListView) findViewById(R.id.listView1);
list.setAdapter(adapter);
} else if(checkedId == R.id.radio1){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.mainitem, items2);
ListView list = (ListView) findViewById(R.id.listView1);
list.setAdapter(adapter);
}
}
如果要在清除RadioGroup选项时隐藏或清除列表,只需要在返回-1时添加额外的if,并对列表视图进行更改。来自android参考:"When the selection is cleared, checkedId is -1."
if (checkedId == -1) { ... }
答案 1 :(得分:0)
无需一次又一次地创建新的listview和适配器实例。每次更新数组列表时,您的列表都需要更新。
String[] items = {"Test", "Test 2", "Test 3"};
String[] items2 = {"Bla", "Bla bla", "Bla bla bla"};
List<String> arrayList1 = new ArrayList( Arrays.asList(items));
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayList1);
ListView list = (ListView) findViewById(R.id.listView1);
list.setAdapter(adapter);
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.radio0){
arrayList1.clear();
arrayList1.addAll(Arrays.asList(items));
} else if(checkedId == R.id.radio1){
arrayList1.clear();
arrayList1.addAll(Arrays.asList(items2));
}
if(adapter != null){
adapter.notifyDataChange();
}
}