-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathAbstractBaseAdapter.java
More file actions
120 lines (97 loc) · 2.77 KB
/
AbstractBaseAdapter.java
File metadata and controls
120 lines (97 loc) · 2.77 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package momo.com.week10_project.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.List;
/**
* 自定义抽象万能 BaseAdapter
* 可传入任意数据源、布局
*/
public abstract class AbstractBaseAdapter<T> extends BaseAdapter{
//数据源
List<T> data;
//LayoutInflater
LayoutInflater inflater;
//布局资源
int[] layoutId;
int countSum = -1;
//构造方法
public AbstractBaseAdapter(Context context, List<T> data ,int ...layoutId) {
this.layoutId = layoutId;
this.data = data;
inflater = LayoutInflater.from(context);
}
/**
* 定义itemCount
*/
public void setCount(int count)
{
countSum = count;
//this.notifyDataSetChanged();
}
@Override
public int getCount() {
if (countSum == -1)
{
return data.size();
}
else
{
return countSum;
}
}
@Override
public Object getItem(int position) {
if (countSum == -1)
{
return data.get(position);
}
else
{
return data.get(countSum % data.size());
}
}
@Override
public long getItemId(int position) {
return position;
}
//重写getViewTypeCount(因为可能传入的布局有多个)
//返回Listview布局种类个数,即布局资源id数组的长度
@Override
public int getViewTypeCount() {
return layoutId.length;
}
//抽象绑定数据的方法
public abstract void bindData(int position, ViewHolder holder);
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
//得到当前数据布局类型
int layoutType = getItemViewType(position);
if (convertView == null) {
//根据类型加载不同的布局
convertView = inflater.inflate(layoutId[layoutType], parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//绑定数据
bindData(position, holder);
return convertView;
}
public static class ViewHolder {
//保存的控件:是需要设置值的控件
private View view;
public ViewHolder(View view) {
this.view = view;
}
//向子类提供一个方法,返回需要设置值的控件
public View findViewById(int viewId) {
//根据viewid,找到对应的控件
return view.findViewById(viewId);
}
}
}