ListView在android中的列表显示。主要是用于数据的显示,通常是从网络上解析出来的数据,显示到ListView上。可以显示很多行,每一行习惯上称之为item。而要控制ListView总共要显示多少个item,以及每个item的布局,则需要使用到适配器------- adapter。
首先使用ArrayAdapter适配器。而ListView和ArrayAdapter将在以下的代码中详细讲解。更多详细的信息,请参考Android官方文档。
MainActivity中的内容如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
package
com.zzh.day_listview;
import
java.util.ArrayList;
import
android.app.Activity;
import
android.os.Bundle;
import
android.view.View;
import
android.widget.AdapterView;
import
android.widget.AdapterView.OnItemLongClickListener;
import
android.widget.ArrayAdapter;
import
android.widget.ListView;
import
android.widget.Toast;
public
class
MainActivity
extends
Activity
{
ListView lv;
ArrayList<String> list =
new
ArrayList<String>();
@Override
protected
void
onCreate(Bundle savedInstanceState)
{
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
// 找到lv的对象
// 初始化list集合。
for
(
int
i =
0
; i <
20
; i++)
{
list.add(
"item -- "
+ i);
}
// 设置ListView的适配器。
/*
* ArrayAdapter构造方法中的参数:
* 参数一:当前上下文路径,即要在哪个Activity中显示。
* 参数二:布局文件的ID。这里使用的是系统提供的
* 。这个布局文件与一般的布局文件不同,ArrayAdapter中,只接收有一个TextView的布局文件
* ,如R.layout.list_item。
* 参数三:要显示的数据集合。在重载的构造方法中:第三个参数还可以是一个数组。
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);// 将适配器注册给ListView
// 给ListView增加长按监听事件.增加点击事件是lv.setOnClickListener();
lv.setOnItemLongClickListener(new OnItemLongClickListener()
{
/**
* 参数一:当前点击的item所在的父控件
* 参数二:当前所点击的那个item对象
* 参数三:所点击的位置。
* */
@Override
public
boolean
onItemLongClick(AdapterView<?> parent, View view,
int
position,
long
id)
{
Toast.makeText(MainActivity.
this
,
"当前点击了第"
+ position+
"项"
,Toast.LENGTH_LONG).show();
return
false
;
}
});
}
}
|
activity_main.xml中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<
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"
>
<
ListView
android:id
=
"@+id/listView1"
android:layout_width
=
"match_parent"
android:layout_height
=
"wrap_content"
android:layout_alignParentTop
=
"true"
android:layout_centerHorizontal
=
"true"
>
</
ListView
>
</
RelativeLayout
>
|
list_item.xml中(不是必须的文件布局):
1
2
3
4
|
<
TextView
xmlns:android
=
"http://schemas.android.com/apk/res/android"
android:id
=
"@+id/textView1"
android:layout_width
=
"wrap_content"
android:layout_height
=
"wrap_content"
/>
|
效果如下图:
本文转自 墨宇hz 51CTO博客,原文链接:http://blog.51cto.com/zzhhz/1631464