1. 程式人生 > >Android示例程式碼:如何實現一個文字列表

Android示例程式碼:如何實現一個文字列表

轉載自碼農場Android示例程式碼:如何實現一個文字列表

在Android應用中,ListView是一個非常有用的控制元件。由於Android手機和普通Android平板電腦的螢幕尺寸有限,我們需要使用列表在有限的空間中顯示足夠都的內容。ListView非常容易使用,並且我們可以自定義ListView內部顯示的列表項。在這個示例程式碼中,我將使用ListView顯示一個文字列表,為大家演示一下ListView的基本用法。

首先,我們先使用XML定義一個程式主介面。介面很簡單,在一個RelativeLayout中放一個ListView,寬度和高度根據實際螢幕尺寸變化。

<!-- activity_postlist.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="@+id/postListView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>

下面,我們需要定義列表項,就是如何在列表中顯示資料。ListView的功能非常強大,我們可以根據不同的情況定義如何顯示資料。在列表項在,我們可以加入文字,圖片,按鈕,甚至動畫。在以後的示例中,我將一一演示。在本示例中,我先介紹給大家如何在列表中顯示文字。

<!-- postitem.xml -->
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/postTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="2"
android:textIsSelectable="false"
android:textSize="16sp" >
</TextView>
我們已經定義好了程式的主介面,以及如何在列表中顯示資料。接下來,我們需要定義一個字元陣列,並且使用ArrayAdapter把陣列顯示在列表中。

package com.jms.rssreader;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private String[] listData = new String[]{"Post 1", "Post 2", "Post 3", "Post 4", "Post 5", "Post 6"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_postlist);
ListView listView = (ListView)this.findViewById(R.id.postListView);
ArrayAdapter<String> itemAdapter = new ArrayAdapter<String>(this, R.layout.postitem, listData);
listView.setAdapter(itemAdapter);
}
}