The Design of Android ListActivity

本文介绍如何使用 Android 的 ListActivity 来展示数据。通过一个简单的例子,演示了如何从 XML 文件中获取数据,并设置适配器将数据展示在 ListView 中。

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

The design of the ListActivity in Android follows the MVC design pattern.

The main parts of a ListActiviy and their relationship is as shown in the following picture:


Now, we will apply a simplest ListActivity, the class diagram is as the following picture:

Since the ListActiviy follows the MVC design pattern. And the ListActivity object has a ListView to display data, and a ListAdapter to provide data to the ListView. So, what we need is the data. In the following example, I will define the data in a XML file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string-array name="keypoints">
		<item>Activity</item>
		<item>Service</item>
		<item>BroadcastReceiver</item>
		<item>ContentProvider</item>
		<item>Intent</item>
	</string-array>
</resources>
Now, we have had the data to display, what should we do in next step is to define our own ListActivity. In the ListActivity, we just do two simply things:

1. get data from XML file;

2. set adapter to this ListActivity.

package org.vhow.android;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AndroidDemoActivity extends ListActivity
{
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		// 1. Get data to be displayed
		String[] keypoints = getResources().getStringArray(R.array.keypoints);

		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, keypoints);
		
		// 2. Set adapter, provides data to the ListView that this ListActiviy contains
		setListAdapter(arrayAdapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		super.onListItemClick(l, v, position, id);
		Object object = getListAdapter().getItem(position);
		Toast.makeText(this, object.toString(), Toast.LENGTH_SHORT).show();
	}
}
Ok, we have created the simpliest ListActivity. Run this program, it will looks like:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值