我正在开发这个联系人应用程序。到目前为止,我已经生成了一个 ListView 女巫,其中包含联系人姓名和电话号码。当您单击联系人时,它会启动新 Activity 并显示联系人姓名和电话号码。
我想做的是,我的 ListView 只显示联系人姓名,当您单击列表中的联系人时, Activity 开始,您可以同时看到姓名和电话号码。
我想也许我可以在 ListView 中隐藏一些信息,但我还没有发现任何好的东西。
那么有人有什么建议吗?
提前致谢。
最佳答案
首先只查询联系人姓名和id:
在你的 list 中你必须声明
<uses-permission android:name="android.permission.READ_CONTACTS" />
public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle){
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
// Returns a new CursorLoader
return new CursorLoader(
getActivity(), // Parent activity context
uri, // Table to query
projection, // Projection to return
null, // No selection clause
null, // No selection arguments
sortOrder // Sort by name
);
}
一旦您获得了带有联系人的 Cursor,您必须将其传递到 CursorAdapter
private final static String[] FROM_COLUMNS = {
Build.VERSION.SDK_INT
>= Build.VERSION_CODES.HONEYCOMB ?
Contacts.DISPLAY_NAME_PRIMARY :
Contacts.DISPLAY_NAME
};
private final static int[] TO_IDS = {
android.R.id.text1
};
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
// Gets the ListView from the View list of the parent activity
mContactsList =
(ListView) getActivity().findViewById(R.layout.contact_list_view);
// Gets a CursorAdapter
mCursorAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.contact_list_item,
null,
FROM_COLUMNS, TO_IDS,
0);
// Sets the adapter for the ListView
mContactsList.setAdapter(mCursorAdapter);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
mAdapter.swapCursor(data);
// The list should now be shown.
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
关于ListView中的Android数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26027131/