我目前的问题是我有一个ListView我现在用来显示我的联系人我想设置onItemClick来获取联系人的名字并将其设置为一个名为p2的TextView,我目前拥有的代码是:
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.setp2);
cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
String[] from = new String[]{ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME};
int[] to = new int[]{R.id.id_text,R.id.name_text};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(setp2.this,R.layout.setp2_layout,cursor,from,to);
ListView list = (ListView)findViewById(R.id.contact_list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
});
}
所以基本上我不确定我需要在onItemClick上做什么,任何帮助都赞赏!
答案 0 :(得分:1)
在onItemClick中,您将获得与该列表项关联的视图实例。从该视图中,您可以获取与其关联的文本并将其设置为p2 TextView。如果我对您的要求的理解是正确的,那么代码将是这样的:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
CharSequence name = ((TextView)view.findViewById(R.id.name_text)).getText();
//Set this to your textview in P2
tvP2.setText(name);
}
});
答案 1 :(得分:0)
设置SimpleCursorAdapter.CursorToStringConverter
并在适配器上进行设置,然后使用convertToString(Cursor cursor)
获取项目点击中的文字:
(Cursor) simple.getItem(position)
答案 2 :(得分:0)
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
cursor.moveToPosition(position);
String name = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
p2.setText(name);
}
});