java使用自定义适配器获取检查项
我有自定义适配器的listview。此listview的每个元素都有复选框。标准功能。GetCheckEditePositions()不起作用
onCreate:
final String[] words = new String[] {
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"
};
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, words);
listView.setAdapter(adapter);
我的适配器:
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
DataBaseHelper myDbHelper;
int id = 1;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.listitem, values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = inflater.inflate(R.layout.listitem, parent, false);
CheckBox checkBox = (CheckBox)rowView.findViewById(R.id.checkBox);
TextView newwordview = (TextView)rowView.findViewById(R.id.newwordview);
newwordview.setText("lalala");
return rowView;
}
}
在这里,我尝试检查项目:
public void addbtnclick(View view){
int cntChoice = listView.getCount();
SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (sparseBooleanArray.get(i) == true) {
String a = listView.getItemAtPosition(i).toString();
myDbHelper.setadd(a, "en");
} else if (sparseBooleanArray.get(i) == false) {
}
}
}
在调试sparseBooleanArray中,始终有0项。 我该怎么办
# 1 楼答案
您可能应该让
Adapter
成为可以保留其选中状态的对象列表,而不是字符串然后:
另外:出于性能原因,您应该重新使用convertView。我建议查看视图持有者模式: How can I make my ArrayAdapter follow the ViewHolder pattern?