android开发步步为营之42:listview的使用(上篇:显示普通文本)

本文介绍了如何在Android应用中使用ArrayAdapter和SimpleCursorAdapter来展示联系人列表数据,包括设计页面、Activity实现以及运行效果。

 ListView列表控件,是非常常见的,比如手机里面的联系人,网上商城的商品,游戏里面的道具,有些是纯文本的,有些是图片+文本,内容较多,所以我写了上下两篇,上篇写显示纯文本的范例。
    需要给listview添加数据,需要使用适配器,文本的,我们使用ArrayAdapter和SimpleCursorAdapter,介绍下,这两个类:
   
(1)、ArrayAdapter:
java.lang.Object
   ↳
android.widget.BaseAdapter
 
   ↳
android.widget.ArrayAdapter<T>
Class Overview

A concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

To use something other than TextViews for the array display, for instance, ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

(2)、SimpleCursorAdapter
java.lang.Object
   ↳
android.widget.BaseAdapter
 
   ↳
android.widget.CursorAdapter
 
 
   ↳
android.widget.ResourceCursorAdapter
 
 
 
   ↳
android.widget.SimpleCursorAdapter
Class Overview

An easy adapter to map columns from a cursor to TextViews or ImageViews defined in an XML file. You can specify which columns you want, which views you want to display the columns, and the XML file that defines the appearance of these views. Binding occurs in two phases. First, if a SimpleCursorAdapter.ViewBinder is available, setViewValue(android.view.View, android.database.Cursor, int) is invoked. If the returned value is true, binding has occured. If the returned value is false and the view to bind is a TextView, setViewText(TextView, String) is invoked. If the returned value is false and the view to bind is an ImageView, setViewImage(ImageView, String) is invoked. If no appropriate binding can be found, an IllegalStateException is thrown. If this adapter is used with filtering, for instance in an AutoCompleteTextView, you can use the SimpleCursorAdapter.CursorToStringConverter and the FilterQueryProvider interfaces to get control over the filtering process. You can refer to convertToString(android.database.Cursor) and runQueryOnBackgroundThread(CharSequence) for more information.

开始我们的范例:
第一步:设计页面
<?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="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
/>
 
第二步:设计Activity ListViewActivity.java
/**
 *
 */
package Test.HelloWorld;
 
import java.util.ArrayList;
import java.util.List;
 
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
 
/**
 * @author zhuzhifei
 *
 */
public class ListViewActivity extends Activity {
    ListView listView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            listView = new ListView(this);
            // 方法一:使用ArrayAdapter 从List获取数据
            // listView.setAdapter(new ArrayAdapter<String>(this,
            // R.layout.listview,
            // getData()));
            // 方法二: 使用SimpleCursorAdapter 从手机联系人列表获取数据
            Cursor cursor = getContentResolver().query(Contacts.CONTENT_URI,
                    null, null, null, null);
            startManagingCursor(cursor);
            ListAdapter listAdapter = new SimpleCursorAdapter(this,
                    R.layout.listview, cursor, new String[] { Contacts.DISPLAY_NAME },
                    new int[] { android.R.id.text1 });
            listView.setAdapter(listAdapter);
 
            setContentView(listView);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
 
    }
 
    private List<String> getData() {
 
        List<String> data = new ArrayList<String>();
 
        data.add("测试数据1");
 
        data.add("测试数据2");
 
        data.add("测试数据3");
 
        data.add("测试数据4");
 
        return data;
 
    }
 
}
 
第三步:AndroidManifest.xml添加我们的Activity
<activity android:name=".ListViewActivity">
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
第四步:运行效果
 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值