http://ycl248.blog.163.com/blog/static/3634280620105410114647/
[功能]
* AdapterView
- ListView
- GridView
- Gallery
- Spinner
* Adapter
- SimpleAdapter
- SimpleCursorAdapter
- ArrayAdapter
至于 AdapterView & Adapter 如何选择的问题 有2点需要注意:
× AdapterView 的选择 只和界面有关 和具体数据无关
× Adapter 的选择 只喝数据有关 和界面无关
二者耦合度高 互不干涉!
android给出的AdapterView中所使用的Adapter的item都是TextView 即 只能显示一下文字信息 这就限制了它的应用 所以现在告诉大家怎么使用别的View
[思路]
1. 自定义一个 extends BaseAdapter 的 class 如 public class CustomList extends BaseAdapter
2. 填充 CustomList 的一些方法 如下:
Java代码
1 public int getCount()
2 public Object getItem(int position)
3 public long getItemId(int position)
4 public View getView(int position, View convertView, ViewGroup parent)
[代码]
1. 比如 现在有下列数据 要求显示之
Java代码
5 String[] week = {
6 "JAN","FEB","MAR","APR",
7 "MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC "
8 };
2. 一些函数的定义如下
Java代码
9 public class CustomList extends BaseAdapter {
10 Activity activity;
11
12 //construct
13 public CustomList(Activity a ) {
14 activity = a;
15 }
16
17 @Override
18 public int getCount() {
19 // TODO Auto-generated method stub
20 return week.length;
21 }
22
23 @Override
24 public Object getItem(int position) {
25 // TODO Auto-generated method stub
26 return week[position];
27 }
28
29 @Override
30 public long getItemId(int position) {
31 // TODO Auto-generated method stub
32 return position;
33 }
34
35 @Override
36 public View getView(int position, View convertView, ViewGroup parent) {
37 // TODO Auto-generated method stub
38 TextView tv = new TextView(activity);
39 tv.setText(week[position]);
40 return tv;
41 }
42
43 }
3. 考虑到美观 我们可以把getView()的一些填充提取出来 即 根据目标的position 得到目标所需View
Java代码
44 public View addCustomView(int position){
45 View view = new View(activity);
46
47 switch(position){
48 case 11:
49 Button btn = new Button(activity);
50 btn.setText("Yes!");
51
52 view = btn;
53 case 12:
54 ImageView iv = new ImageView(activity);
55 iv.setImageResource(R.drawable.robot);
56
57 view = iv;
58
59 break;
60 default:
61 TextView tv = new TextView(activity);
62 tv.setGravity(1);
63 tv.setText(week[position]);
64 tv.setPadding(5, 5, 5, 5);
65 view = tv;
66 }
67
68 return view;
69 }
4. 如何使用
Java代码
70 public View getView(int position, View convertView, ViewGroup parent) {
71 // TODO Auto-generated method stub
72 return addCustomView(position);
73 }