List View //API Guides Layouts List View

本文介绍如何使用CursorLoader异步加载数据到ListView中,并提供了一个完整的示例代码,该示例展示了如何实现LoaderCallbacks接口来更新ListView的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

List  View  //API Guides

ListView  is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an  Adapter  that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list.

//ListView是一个可以展示一列可滚动条目的视图组。列表项可以自动加入列表通过使用Adapter.这个Adapter从一个源,例如一个数组或者数据库查询拉来内容并且将每一项转变成一个视图放置在列表上。
For an introduction to how you can dynamically insert views using an adapter, read Building Layouts with an Adapter.
//读"Building Layouts with an adapter"可以看到一个例子,这个例子会告诉你如何动态地插入视图通过一个适配器.

Using a Loader//使用一个Loader

Using a  CursorLoader  is the standard way to query a  Cursor  as an asynchronous task in order to avoid blocking your app's main thread with the query. When the  CursorLoader  receives the  Cursor  result, the  LoaderCallbacks  receives a callback to  onLoadFinished() , which is where you update your  Adapter  with the new  Cursor  and the list view then displays the results.
//为了避免你的应用因为查询阻塞主线程,一个标准的方法是使用一个CursorLoader去查询一个Cursor作为一个异步任务。当CursorLoader接收到一个Cursor结果,LoaderCallbacks接收到一个回调方法onLoadFinished(),这里就是你使用一个新的Cursor更新你的Adapter并且列表视图会展现这个结果。
Although the CursorLoader APIs were first introduced in Android 3.0 (API level 11), they are also available in theSupport Library so that your app may use them while supporting devices running Android 1.6 or higher.
//尽管CursorLoader APIS 是在Android 3.0(API level 11)里第一次被引进的,但是它们在Support Library里面是可以使用的,所以你的应用可以使用它们支持设备运行Android 1.6或者更高版本。
For more information about using a Loader to asynchronously load data, see the Loaders guide.
//使用Loader去异步地装载数据的更多的信息,见Loaders指南。

Example

The following example uses  ListActivity , which is an activity that includes a  ListView  as its only layout element by default. It performs a query to the  Contacts Provider  for a list of names and phone numbers.
//下面的例子使用了ListActivity,这个Activity包含一个ListView默认地作为它唯一的布局元素。它对Contacts Provider执行了一个查询,得到电话号码和姓名的列表。
The activity implements the LoaderCallbacks interface in order to use a CursorLoader that dynamically loads the data for the list view.
//这个activity实现了LoaderCallbacks接口,为了使用CursorLoader异步地加载数据为列表。

public class ListViewLoader extends ListActivity
        implements LoaderManager.LoaderCallbacks<Cursor> {

    // This is the Adapter being used to display the list's data
    SimpleCursorAdapter mAdapter;

    // These are the Contacts rows that we will retrieve
    static final String[] PROJECTION = new String[] {ContactsContract.Data._ID,
            ContactsContract.Data.DISPLAY_NAME};

    // This is the select criteria
    static final String SELECTION = "((" + 
            ContactsContract.Data.DISPLAY_NAME + " NOTNULL) AND (" +
            ContactsContract.Data.DISPLAY_NAME + " != '' ))";

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

        // Create a progress bar to display while the list loads
        ProgressBar progressBar = new ProgressBar(this);
        progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, Gravity.CENTER));
        progressBar.setIndeterminate(true);
        getListView().setEmptyView(progressBar);

        // Must add the progress bar to the root of the layout
        ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
        root.addView(progressBar);

        // For the cursor adapter, specify which columns go into which views
        String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME};
        int[] toViews = {android.R.id.text1}; // The TextView in simple_list_item_1

        // Create an empty adapter we will use to display the loaded data.
        // We pass null for the cursor, then update it in onLoadFinished()
        mAdapter = new SimpleCursorAdapter(this, 
                android.R.layout.simple_list_item_1, null,
                fromColumns, toViews, 0);
        setListAdapter(mAdapter);

        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(0, null, this);
    }

    // Called when a new Loader needs to be created
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // Now create and return a CursorLoader that will take care of
        // creating a Cursor for the data being displayed.
        return new CursorLoader(this, ContactsContract.Data.CONTENT_URI,
                PROJECTION, SELECTION, null, null);
    }

    // Called when a previously created loader has finished loading
    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);
    }

    // Called when a previously created loader is reset, making the data unavailable
    public void onLoaderReset(Loader<Cursor> loader) {
        // This is called when the last Cursor provided to onLoadFinished()
        // above is about to be closed.  We need to make sure we are no
        // longer using it.
        mAdapter.swapCursor(null);
    }

    @Override 
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Do something when a list item is clicked
    }
}
Note:  Because this sample performs a query on the  Contacts Provider , if you want to try this code, your app must request the  READ_CONTACTS  permission in the manifest file:
<uses-permission android:name="android.permission.READ_CONTACTS" />
//注意:因为这个例子在Contacts Provider里面执行了查询,所以如果你想要试一试这个代码,你的应用必须在manifest file请求READ_CONTACTS的权限:<uses-permission android:name="android.permission.READ_CONTACTS" />




说明:上面例子里面引入的包:
import android.app.ListActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
这个例子将手机上的联系人的姓名在一个ListView里面显示了出来.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值