我需要根据用户选择的联系人组以编程方式检查或取消选中联系人列表。getView()
根据我从这个论坛得到的一些建议,我应该在bindView()
扩展的适配器中实现逻辑SimpleCursorAdapter
。但是,下面显示的代码似乎不起作用。屏幕上的联系人列表是空白的。你能告诉我我做错了什么吗?
public View getView(int position, View convertView, ViewGroup viewGroup) {
ContactViewHolder holder = null;
CheckedTextView tv = null;
if (convertView == null) {
int layout = android.R.layout.simple_list_item_multiple_choice;
convertView = mInflater.inflate(layout, viewGroup, false);
holder = new ContactViewHolder();
tv = (CheckedTextView) convertView.findViewById(android.R.id.text1);
holder.checkedTextView = tv;
holder.position = position;
holder.displayName = contactList.get(position);
holder.checked = tv.isChecked();
convertView.setTag(holder);
contactListMap.put(position, holder);
} else {
holder = (ContactViewHolder) convertView.getTag();
}
ContactViewHolder value = contactListMap.get(position);
holder.checkedTextView = value.checkedTextView;
// holder.checkedTextView.setChecked(value.checked);
return convertView;
}
公共类 ContactViewHolder {
public String contactId;
public String displayName;
public int position;
public boolean checked;
public CheckedTextView checkedTextView;
}
在扩展 ListFragment 的片段类中加载联系人的代码片段实现了 LoaderCallbacks
private static final String[] PROJECTION = {Contacts._ID, // _ID 始终是必需的 Contacts.DISPLAY_NAME_PRIMARY // 这就是我们要显示的内容 };
// and name should be displayed in the text1 textview in item layout
private static final String[] FROM = {Contacts.DISPLAY_NAME_PRIMARY};
private static final int[] TO = {android.R.id.text1};
private static String SORT_ORDER = Contacts.SORT_KEY_PRIMARY;
private static String SELECTION = Contacts.DISPLAY_NAME_PRIMARY + "<>''" + " AND " + Contacts.IN_VISIBLE_GROUP
+ "=1";
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// load from the "Contacts table"
Uri contentUri = Contacts.CONTENT_URI;
// no sub-selection, no sort order, simply every row
// projection says we want just the _id and the name column
return new CursorLoader(getActivity(), contentUri, PROJECTION, null, null, SORT_ORDER);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Once cursor is loaded, give it to adapter
Map<String, Integer> allContacts = new HashMap<String, Integer>();
mAdapter.swapCursor(data);
List<String> contactList = new ArrayList<String>();
for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
String contactId = data.getString(data.getColumnIndex(Contacts._ID));
String display = data.getString(data.getColumnIndex(Contacts.DISPLAY_NAME_PRIMARY));
contactList.add(display);
}
mAdapter.setContactList(contactList);
//mCallback.setInitialContactList(allContacts);
}
我必须执行上述代码的原因是要设置 check on checkedTextView
,我想我需要调用:
getListView().setItemChecked(positon, true);
但是,我只知道光标的位置,不知道ListView
. 无论如何可以根据光标位置找到列表视图位置?如果是这样,我什至不需要上面的getView()
代码。
另外,我应该覆盖getView()
还是bindView()
?bindView 没有位置,所以我不能 cal getListView().setItemChecked(position, true)
。对不同方法有什么建议吗?
这似乎是一个非常常见的用例。但是我花了很多天尝试不同的东西,但它仍然不起作用。请帮我。非常感谢!