Подтвердить что ты не робот

Как отображать контакты в списке в Android для Android api 11+

Мне жаль, если это похоже на один вопрос в миллион раз... но поиск в Google для этого не дает никаких результатов, просто куча устаревших руководств с использованием managedQuery и других устаревших решений...

Я прошел обучение

в my 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?

4b9b3361

Ответ 1

Небольшой урезанный пример для отображения имени контакта в ListView. Ниже Fragment extends ListFragment, который имеет макет по умолчанию. Вам не нужно указывать свои собственные. Макет для элементов списка также берется из макетов по умолчанию для Android (android.R.layout.simple_list_item_1), который представляет собой простую одну строку текста для каждого элемента.

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;

public class ContactListFragment extends ListFragment implements LoaderCallbacks<Cursor> {

    private CursorAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // create adapter once
        Context context = getActivity();
        int layout = android.R.layout.simple_list_item_1;
        Cursor c = null; // there is no cursor yet
        int flags = 0; // no auto-requery! Loader requeries.
        mAdapter = new SimpleCursorAdapter(context, layout, c, FROM, TO, flags);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // each time we are started use our listadapter
        setListAdapter(mAdapter);
        // and tell loader manager to start loading
        getLoaderManager().initLoader(0, null, this);
    }

    // columns requested from the database
    private static final String[] PROJECTION = {
        Contacts._ID, // _ID is always required
        Contacts.DISPLAY_NAME_PRIMARY // that what we want to display
    };

    // and name should be displayed in the text1 textview in item layout
    private static final String[] FROM = { Contacts.DISPLAY_NAME_PRIMARY };
    private static final int[] TO = { android.R.id.text1 };

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {

        // load from the "Contacts table"
        Uri contentUri = Contacts.CONTENT_URI;

        // no sub-selection, no sort order, simply every row
        // projection says we want just the _id and the name column
        return new CursorLoader(getActivity(),
                contentUri,
                PROJECTION,
                null,
                null,
                null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // Once cursor is loaded, give it to adapter
        mAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // on reset take any old cursor away
        mAdapter.swapCursor(null);
    }
}