在你的活動
private String [] project = {ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
...
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
project, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
startManagingCursor(phones);
ContactCursorAdapter adapter = new ContactCursorAdapter(this, phones);
ListView contactLV = (ListView) findViewById(R.id.contactLV);
contactLV.setAdapter(adapter);
...
你自己的光標適配器類
public class ContactCursorAdapter extends CursorAdapter {
public ContactCursorAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView nameTV = (TextView)view.findViewById(R.id.nameTV);
nameTV.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
TextView phoneTV = (TextView)view.findViewById(R.id.phoneTV);
phoneTV.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.contact_for_lv, parent, false);
bindView(v, context, cursor);
return v;
}
}
XML的ListView控件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="@+id/nameTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/phoneTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="14sp" />
</LinearLayout>
感謝烏拉圭回合的答案,但請你解釋一下,我沒有得到它,我應該在哪裏定義的TextView?在哪個XML文件中,在我的XML文件中沒有TextView,它只包含ListView和一些按鈕。 – developer
您必須在contact_for_lv.xml文件中定義TextView。有些視圖可能是ListView的項目(行)。 – prozhyga