如果这看起来像同一个问题一百万次,我很抱歉......但是谷歌搜索没有提供任何结果,只是一堆过时的教程使用managedQuery
以及其他已弃用的解决方案...
我经历了用于检索联系人列表的 Android 开发人员培训 http://developer.android.com/training/contacts-provider/retrieve-names.html,但教程不完整,甚至下载示例代码也无济于事,因为示例代码用于更高级的联系人列表操作(搜索等)
无论如何,没有理由不应该有一个简单的解决方案,所以我希望有人可以在这里回答,因为我确信这已经被完成了一百万次,而且我确信还有数十个其他初级 Android 开发人员会很感激这一点。
据我所知,我已按照教程进行操作,但没有出现任何联系人。我认为最重要的是TO_IDS
是一个整数数组,指向android.R.id.text1
。我很困惑这应该如何以某种方式提取联系人姓名数组。
另外,我很困惑为什么当最终目标是显示列表视图时需要文本视图...在教程中,我们有 mContactsList 这是一个列表视图...但是我们使用指向的适配器填充列表视图R.layout.contact_list_item
这只是由 TO_IDS(整数数组)填充的文本视图。
mContactsList = (ListView) getActivity().findViewById(R.layout.contact_list_view);
mCursorAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.contact_list_item,
null,
FROM_COLUMNS, TO_IDS,
0);
mContactList.setAdapter(mCursorAdapter);
我做错了什么以及如何在列表视图中简单地显示联系人列表?
编辑:添加我的代码:
在我的片段类中:
public class MyFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>{
private static final String[] FROM_COLUMNS = {ContactsContract.Contacts.DISPLAY_NAME_PRIMARY };
private static final int[] TO_IDS = {android.R.id.text1};
ListView mContactList;
private SimpleCursorAdapter mCursorAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.contact_list_view,container,false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
mContactsList = (ListView) getActivity().findViewById(R.layout.contact_list_view);
mCursorAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.contact_list_item,
null,
FROM_COLUMNS, TO_IDS,
0);
mContactList.setAdapter(mCursorAdapter);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
}
在我的 Activity_main.xml 中:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id ="@+id/contactListFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="preamble.myapp.MyFragment"/>
</LinearLayout>
在我的 contact_list_view xml 中:
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
在我的 contact_list_item xml 中
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
最后对于 contact_list_layout xml:
我在里面放什么contact_list_layout.xml
?难道这只是一个空<LinearLayout>
?教程中并不清楚如何处理此 xml。它说这个 XML 是片段,但是如果它是片段,为什么我们要定义一个listview
已经在contact_list_view.xml
?