Android:从使用光标创建的列表对话框中获取所选项目的ID

时间:2012-03-18 20:39:41

标签: android listview dialog contacts

在我的Activity类中,我正在覆盖onCreateDialog()方法 代码有点像下面所示。 对话框现在列出了我的联系人列表中的所有项目。

当用户点击此列表中的项目时,我想获取联系人ID 点击的项目,即字段Phone._ID的值。

目前我只获得所选项目的位置(索引) OnClickListener的which参数。 如果列表显示在ListActivity中,我可以使用:

getListView().getItemIdAtPosition(which);

但是在这里我无法获得对ListView的引用。 如何从使用光标创建的列表对话框中获取所单击项目的ID。

protected Dialog onCreateDialog(int id) {
  String[] projection = new String[] {
                Phone._ID,
                Phone.DISPLAY_NAME,
                Phone.NUMBER
        };
  Cursor cursor = managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                projection, null, null, null);
  return new AlertDialog.Builder(ContactActivity.this)
            .setTitle("Select Contacts")
            .setCursor(cursor,
               new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {

               /* User clicked on a contact item */

               Toast.makeText(getApplicationContext(), 
                            "CLICKED-"+which,
            Toast.LENGTH_SHORT).show();

            }
               }, ContactsContract.Contacts.DISPLAY_NAME)
           .create();

}

提前致谢

1 个答案:

答案 0 :(得分:0)

我自己找到了解决方案。下面是我现在使用的代码。

我已将联系人列表查询的光标声明为final。 并在onClick方法中使用相同的游标对象 使用moveToPosition()方法获取点击位置的记录 光标。 另请注意,我必须在底部使用cursor.moveToFirst(); onClick。否则当我调用时,对话框显示为空 再次对话(我不确定为什么会这样)。

protected Dialog onCreateDialog(int id) {
String[] projection = new String[] {
            Phone._ID,
            Phone.DISPLAY_NAME,
            Phone.NUMBER
    };
final Cursor cursor = managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            projection, null, null, null);
return new AlertDialog.Builder(ContactActivity.this)
        .setTitle("Select Contacts")
        .setCursor(cursor,
        new DialogInterface.OnClickListener() {

          public void onClick(DialogInterface dialog, int which) {

           /* User clicked on a contact item */
            if(cursor.moveToPosition(which)){

             long contactId=cursor.getLong(0);
             String name=cursor.getString(1);
             String number=cursor.getString(2);
             Toast.makeText(getApplicationContext(),
                     "You selected: ["+contactId+"]" 
                      + name + " , " +number,
                     Toast.LENGTH_SHORT)
                   .show();
            }
            cursor.moveToFirst();//Reset the position

          }
       }, ContactsContract.Contacts.DISPLAY_NAME)
       .create();

}

但我觉得这不是正确的做法。 所以我并不认为这是这个问题的答案。 我会暂时搁置这个问题并希望 有人可以提出更好的建议。

更新:标记为答案,因为没有回复。

相关问题