publicclass MyListViewBase
extends
Activity {
private
ListView lv;
ArrayList<HashMap<String, Object>>listItem;
/** Called when the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) findViewById(R.id.lv);
MyAdapter mAdapter =
new
MyAdapter(
this
);
lv.setAdapter(mAdapter);
/**为ListView添加点击事件*/
lv.setOnItemClickListener(
new
OnItemClickListener() {
@Override
publicvoid onItemClick(AdapterView<?> arg0, View arg1,
int
arg2,
long
arg3) {
Log.v(
"MyListViewBase"
,
"你点击了ListView条目"
+ arg2);
}
});
}
/**添加一个得到数据的方法,方便使用*/
private
ArrayList<HashMap<String, Object>> getDate(){
ArrayList<HashMap<String, Object>> listItem =
new
ArrayList<HashMap<String,Object>>();
/**为动态数组添加数据*/
for
(
int
i=
0
;i<
30
;i++)
{
HashMap<String, Object> map =
new
HashMap<String, Object>();
map.put(
"ItemTitle"
,
"第"
+i+
"行"
);
map.put(
"ItemText"
,
"这是第"
+i+
"行"
);
listItem.add(map);
}
return
listItem;
}
/** 新建一个类继承BaseAdapter,实现视图与数据的绑定
*/
privateclass MyAdapter
extends
BaseAdapter {
private
LayoutInflater mInflater;
/**构造函数*/
public
MyAdapter(Context context) {
this
.mInflater = LayoutInflater.from(context);
}
@Override
publicint getCount() {
return
getDate().size();
}
@Override
public
Object getItem(
int
position) {
returnnull;
}
@Override
publiclong getItemId(
int
position) {
return
0
;
}
/**书中详细解释该方法*/
@Override
public
View getView(finalint position, View convertView, ViewGroup parent) {
ViewHolder holder;
Log.v(
"MyListViewBase"
,
"getView "
+ position +
" "
+ convertView);
if
(convertView ==
null
) {
convertView = mInflater.inflate(R.layout.item,
null
);
holder =
new
ViewHolder();
/**得到各个控件的对象*/
holder.title = (TextView) convertView.findViewById(R.id.ItemTitle);
holder.text = (TextView) convertView.findViewById(R.id.ItemText);
holder.bt = (Button) convertView.findViewById(R.id.ItemButton);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
/**设置TextView显示的内容,即我们存放在动态数组中的数据*/
holder.title.setText(getDate().get(position).get(
"ItemTitle"
).toString());
holder.text.setText(getDate().get(position).get(
"ItemText"
).toString());
/**为Button添加点击事件*/
holder.bt.setOnClickListener(
new
OnClickListener() {
@Override
publicvoid onClick(View v) {
Log.v(
"MyListViewBase"
,
"你点击了按钮"
+ position);
}
});
return
convertView;
}
}
/**存放控件*/
publicfinalclass ViewHolder{
public
TextView title;
public
TextView text;
public
Button bt;
}
}