我有一个扩展 ListActivity 的类,它包含一个通过对象的 ArrayList 填充的 ListView 和一个我创建的自定义适配器,它是 ArrayAdapter 的子类。
我想要对象的一个字段来引用对象行是否应该被选中。
然后当 ListView 被填充时,一些行将被预选(选中)
我已经覆盖了 ArrayAdapter.getView() 以便我可以通过一个对象来填充我的布局。
我以为我会在这里设置要检查或不检查的行 - 但我想不出解决方案 - 有什么想法吗?
这是我的 getView() 代码:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.contactedit_onerow, null);
}
ContactVO mObject = items.get(position);
if (mObject != null) {
CheckedTextView nameV = (CheckedTextView) convertView.findViewById(R.id.rowText1);
TextView phoneV = (TextView) convertView.findViewById(R.id.rowText2);
TextView emailV = (TextView) convertView.findViewById(R.id.rowText3);
TextView headerV = (TextView) convertView.findViewById(R.id.alphaHeader);
if (alphaIndexer.get(mObject.name.substring(0, 1).toUpperCase()) == position ) {
headerV.setText(mObject.name.substring(0,1));
headerV.setVisibility(View.VISIBLE);
} else {
headerV.setText("");
headerV.setVisibility(View.GONE);
}
nameV.setText(mObject.name);
phoneV.setText("Phone: " + mObject.phone);
emailV.setText("Email: " + (mObject.email != null ? mObject.email : ""));
// THE FOLLOWING LINE UNCOMMENTED DOES NOTHING
// (any suggestions to make it work)
// nameV.setChecked(true);
}
return convertView;
}
提前致谢!
最佳答案
我仍然不知道如何预先选择项目因为适配器正在填充 ListView,从而避免以后必须迭代 ArrayList 数据源。
然而,这里有一个解决方案应该与由对象 ArrayList 支持的 ListView 一起使用:
// In an activity that extends ListActivity
// With a CustomAdapter that extends ArrayAdpater
ArrayList arrayList = createArrayListOfObjectsForListView();
CustomAdapter mAdapter = new CustomAdapter(this, R.layout.mLayout, arrayList);
setListAdapter(mAdapter);
// Iterate over arrayList to check if item/row should be pre selected in the ListView
int j = 0;
for (Object item : arrayList) {
// Check a field/condition in the object
if (item.selected == true) {
listView.setItemChecked(j,true);
}
j++;
}
或者,我亲自检查我的对象的 ID 是否与一组选定的 ID 匹配,所以我的 for 循环看起来像这样:
int j = 0;
for (Object item : arrayList) {
if (mySet.contains(item.id)) {
listView.setItemChecked(j, true);
}
j++;
}
关于android - 在填充 ListView 时通过适配器检查 CheckedTextView 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5242142/