Chendd's Blog

世界上没有什么事情是一行代码不能解决的。如果有,那就两行。

Android学习日记3--常用控件ListView

常用控件

8、ListView

       列表视图,比如游戏的排行榜。列表数据可以根据屏幕大小自适应

列表的显示需要三个元素:

  • ListVeiw:用来展示列表的View。

  • 适配器:用来把数据映射到ListView上的中介。

  • 数据:具体的将被映射的字符串,图片,或者基本组件。

ListView用到两种适配器: - ArrayAdapter–简单适配器,只显示文字

image

  • SimpleAdapter–自定义适配器,可以显示自定义内容

image

  • SimpleCursorAdapter可以认为是SimpleAdapter对数据库的简单结合,可以方面的把数据库的内容以列表的形式展示出来,暂时不讲。

       使用简单适配器可直接

1
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);

this:当前context android.R.layout.simple_list_item_1是系统的布局文件 list:ListView的各项数据

SimpleAdapter各项参数

1
new SimpleAdapter(context, data, resource, from, to)

context:当前context内容 data:ListView的各项数据 resource:ListView的每项布局 from:ListView的组件索引 to:ListView的组件ID 如:

1
2
new SimpleAdapter(MainActivity.this, list, R.layout.activity_main, new String[] {"item1","item2","item3","item4","item5"}
, new int[] {R.id.iv,R.id.bigtv,R.id.smalltv,R.id.btn,R.id.cb});

但是SimpleAdapter 不能触发组件的事件,还需 自己写适配器继承BaseAdapter

BaseAdapter主要有四个方法 getCount –列表每一项的长度 getItem getItemId getView –绘制每一项的具体组件

例子演示自定义MyAdapter

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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:id="@+id/bigtv"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10sp"
        android:id="@+id/smalltv"
        />

    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button"
        android:id="@+id/btn"
        android:focusable="false"
        />

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cb"
        android:focusable="false"
        />


</LinearLayout>

布局文件要特别说明两个属性

1
2
android:textSize="10sp" --设置text的大小
android:focusable="false" --设置焦点属性不可见
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.example.listview2;

import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {


    private LayoutInflater mInflater;
    private List<Map<String, Object>> list;
    private int layId;
    private String flag[];
    private int itemId[];



    public MyAdapter(Context context, List<Map<String, Object>> list,
            int layId, String[] flag, int itemId[]) {
        this.mInflater = LayoutInflater.from(context);
        this.list = list;
        this.layId = layId;
        this.flag = flag;
        this.itemId = itemId;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
        // TODO Auto-generated method stub
        arg1 = mInflater.inflate(layId, null);
        for (int i = 0; i < flag.length; i++) {
            if (arg1.findViewById(itemId[i]) instanceof ImageView) {
                ImageView iv = (ImageView)arg1.findViewById(itemId[i]);
                iv.setBackgroundResource((Integer) list.get(arg0).get(flag[i]));
            }else if (arg1.findViewById(itemId[i]) instanceof TextView) {
                TextView tv = (TextView)arg1.findViewById(itemId[i]);
                tv.setText((String)list.get(arg0).get(flag[i]));
            }
        }

        ((Button) arg1.findViewById(R.id.btn))
            .setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new AlertDialog.Builder(MainActivity.ma)
                .setTitle("自定义SimpleAdapter")
                .setMessage("按钮成功触发监听事件!")
                .show();
            }
        });
        CheckBox cb = (CheckBox) arg1.findViewById(R.id.cb);

        cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                new AlertDialog.Builder(MainActivity.ma)
                .setTitle("自定义 adapter")
                .setMessage("触发选择框")
                .show();
            }
        });

        return arg1;
    }

}

MyAdapter代码里

1
2
3
4
new AlertDialog.Builder(MainActivity.ma)
.setTitle("自定义 adapter")
.setMessage("触发选择框")
.show();

       表示弹出对话框,与Toast不同的是 该对话框要按返回才会退出,而Toast是一闪而过的,对话框在下一讲详细阐述 MainActivity.ma是定义在MainActivity的静态变量指向this自己

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
package com.example.listview2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {
    private ListView lv;
    private List<Map<String, Object>> list;
    //private SimpleAdapter sp;
    public static MainActivity ma;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ma = this;

        lv = new ListView(this);

        list = new ArrayList<Map<String,Object>>();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("item1", R.drawable.ic_launcher);
        map.put("item2", "bigtv");
        map.put("item3", "smalltv");

        list.add(map);


        //sp = new SimpleAdapter(MainActivity.this, list, R.layout.activity_main, new String[] {"item1","item2","item3","item4","item5"}, new int[] {R.id.iv,R.id.bigtv,R.id.smalltv,R.id.btn,R.id.cb});
        //lv.setAdapter(sp);

           // --使用自定义适配器,可监听其ListView中每一项的事件监听
        MyAdapter adapter = new MyAdapter(this, list, R.layout.activity_main, new String[] {"item1","item2","item3"}, new int[] {R.id.iv,R.id.bigtv,R.id.smalltv});
             // 为列表视图设置适配器(将数据映射到列表视图中)
            lv.setAdapter(adapter);
             // //显示列表视图

        this.setContentView(lv);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

运行效果 image

Comments