如何在从电话中检索的联系人列表上设置Click侦听器

时间:2018-10-25 16:27:00

标签: android onclicklistener

我已经使用光标和simplecursorAdaptor从手机中将联系人检索到列表视图中。 现在,我想在已检索到的联系人列表上设置onClickListener,这只会举起联系人信息(例如联系人姓名,联系人编号)

我试图在联系人列表上设置一个侦听器,但每次都失败

请帮助, 这是我的代码

    ListView contact_list;
    contact_list=(ListView)findViewById(R.id.list_contacts);
    Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
    startManagingCursor(cursor);

    String[] from= {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone._ID};

    int[] to= {android.R.id.text1,android.R.id.text2};

    final SimpleCursorAdapter simpleCursorAdapter =new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2, cursor,from,to);
    contact_list.setAdapter(simpleCursorAdapter);
    contact_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

XML代码-:

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout 
       xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:app="http://schemas.android.com/apk/res-auto"
       xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       tools:context=".ContactsActivity">

       <ListView
       android:id="@+id/list_contacts"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />
       </LinearLayout>

1 个答案:

答案 0 :(得分:1)

点击侦听器在ListView上设置为:

contact_list.setOnItemClickListener((list, view, pos) -> {
     Cursor item = list.getAdapter().getItem(pos);
     // you have the item clicked and do something
};