[英]How to keep checkbox selection on listview items after adding and sorting?
This is a ListView using a multiple choice adapter. 这是一个使用多选适配器的ListView。
public class ExampleActivity extends ListActivity {
private ListView list;
private List<String> items;
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_example);
this.list = this.getListView();
this.items = new ArrayList<String>();
this.items.add("A");
this.items.add("C");
this.items.add("D");
this.items.add("D");
this.adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, items);
this.list.setAdapter(adapter);
this.user(); // simulating user selecting C
this.button(); // simulating user press some button who adds items to list
}
private void user() {
this.list.setItemChecked(1, true);
}
private void button() {
this.items.add("B");
Collections.sort(this.items);
this.adapter.notifyDataSetChanged();
}
}
If user selects C (index 1), and if then user press button to add items to list and sort (like B), B (new index 1) is going to be selected instead of C. How can this issue be solved? 如果用户选择C(索引1),然后用户按按钮将项目添加到列表和排序(如B),则将选择B(新索引1)代替C。如何解决此问题?
This is because you make selection for index 1 这是因为您选择了索引1
this.list.setItemChecked(1, true); // selects C
and after make the insertion and sort , B
is the item with index 1
并且在进行插入和排序之后,
B
是索引为1
的项目
try this 尝试这个
this.list.setItemChecked(this.list.indexOf("c"),true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.