点击列表项后无法获取列表项信息
到目前为止,我已经看了很多溢出问题,我不知道我的 ListView 是否设置正确,但我不想弄乱我是如何获得联系人的
public class ViewContacts extends AppCompatActivity {
private ListView lv;
private Cursor cursor1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_contacts);
cursor1 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor1);
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 listAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor1, from, to);
ListView lv = findViewById(R.id.list);
lv.setAdapter(listAdapter);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog.Builder option = new AlertDialog.Builder(ViewContacts.this);
option.setMessage(the phone number);
option.show();
}
});
}
}
点击列表项,然后弹出显示电话号码
最佳答案
如果你想要你点击的联系人项目的电话号码,你需要使用position
将光标移动到相应的行,然后获取该项目来自所需的列。
下面是您放入 onItemClick
中的简化示例:
cursor1.moveToPosition(position);
String phoneNumber = cursor1.getString(cursor1.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
您可以将 ContactsContract.CommonDataKinds.Phone.NUMBER
替换为任何有效的列名。
关于android - 如何单击 ListView 项并获取电话号码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54411680/