在开发中,我们经常使用到ListView这个控件。Android的API也提供了许多创建ListView适配器的快捷方式。例如ArrayAdapter、SimpleAdapter和SimpleCursorAdapter等。但你是否发现,如果采用这些系统自带的适配器,对于事件的响应只能局限在一个行单位。假设一行里面有一个按钮和一个图片控件,它们之间的响应操作是不一样的。若采用系统自带的适配器,就不能精确到每个控件的响应事件。这时,我们一般采取自定义适配器来实现这个比较精确地请求。
ListView的创建,一般要具备两大元素:
1)数据集,即要映射的字符串、图片信息之类。
2)适配器,实现把要映射的字符串、图片信息映射成视图(如Textview、Image等组件),再添加到ListView中。
下面是一个实操例子:
实现细节:
1、创建数据集,一般定义如下
private List<Map<String, Object>> listItems;
元素添加方式:
Map<String, Object> map = new HashMap<String, Object>();
map.put("image", imgeIDs[i]); //图片资源
map.put("title", "物品名称:"); //物品标题
map.put("info", goodsNames[i]); //物品名称
map.put("detail", goodsDetails[i]); //物品详情
listItems.add(map); //添加一项
2、创建适配器
public class ListViewAdapter extends BaseAdapter{........} //自定义的适配器一般继承BaseAdapter类
listViewAdapter = new ListViewAdapter(this, listItems);
3、给ListView设置适配器
listView.setAdapter(listViewAdapter);
4、这里还有个关键点,如何把list_item.xml布局作为一个视图,添加到listView中:
LayoutInflater listContainer; //视图容器工厂
listContainer = LayoutInflater.from(context); //创建视图容器工厂并设置上下文
convertView = listContainer.inflate(R.layout.list_item, null); //创建list_item.xml布局文件的视图
实例视图如下:
1)布局文件main.xml
view
plaincopy
to clipboard
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- 结算 -->
<LinearLayout android:gravity="center_horizontal"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:text="结算: "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:textSize="20px"/>
<ImageButton android:id="@+id/imgbt_sum"
android:layout_width="40px"
android:layout_height="40px"
android:background = "@drawable/shopping" />
</LinearLayout>
<TextView android:text="商品列表: "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF" />
<!-- 商品列表 -->
<ListView android:id="@+id/list_goods"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
[xhtml] view
plaincopy
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"> <!-- 结算 --><LinearLayout android:gravity="center_horizontal"android:orientation="horizontal" android:layout_width="fill_parent"android:layout_height="wrap_content"><TextView android:text="结算: "android:layout_width="wrap_content"android:layout_height="wrap_content" android:textColor="#FFFFFFFF" android:textSize="20px"/><ImageButton android:id="@+id/imgbt_sum" android:layout_width="40px"android:layout_height="40px"android:background = "@drawable/shopping" /></LinearLayout><TextView android:text="商品列表: "android:layout_width="wrap_content"android:layout_height="wrap_content" android:textColor="#FFFFFFFF" /><!-- 商品列表 --><ListView android:id="@+id/list_goods" android:layout_width="fill_parent"android:layout_height="wrap_content" /></LinearLayout>
列表项布局文件list_item.xml
view
plaincopy
to clipboard
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- 商品图片 -->
<ImageView android:id="@+id/imageItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5px"/>
<!-- 商品信息 -->
<LinearLayout android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:id="@+id/titleItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:textSize="13px" />
<TextView android:id="@+id/infoItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:textSize="22px" />
</LinearLayout>
<!-- 购买和商品详情 -->
<LinearLayout android:gravity="right"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<CheckBox android:id="@+id/checkItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5px"/>
<Button android:id="@+id/detailItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5px"/>
</LinearLayout>
</LinearLayout>
[xhtml] view
plaincopy
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal" android:layout_width="fill_parent"android:layout_height="fill_parent"><!-- 商品图片 --><ImageView android:id="@+id/imageItem" android:layout_width="wrap_content"android:layout_height="wrap_content" android:layout_margin="5px"/><!-- 商品信息 --><LinearLayout android:orientation="vertical"android:layout_width="wrap_content" android:layout_height="wrap_content"><TextView android:id="@+id/titleItem" android:layout_width="wrap_content"android:layout_height="wrap_content" android:textColor="#FFFFFFFF"android:textSize="13px" /><TextView android:id="@+id/infoItem" android:layout_width="wrap_content"android:layout_height="wrap_content" android:textColor="#FFFFFFFF"android:textSize="22px" /></LinearLayout><!-- 购买和商品详情 --><LinearLayout android:gravity="right"android:orientation="horizontal" android:layout_width="fill_parent"android:layout_height="wrap_content"><CheckBox android:id="@+id/checkItem" android:layout_width="wrap_content"android:layout_height="wrap_content" android:layout_margin="5px"/><Button android:id="@+id/detailItem" android:layout_width="wrap_content"android:layout_height="wrap_content" android:layout_margin="5px"/></LinearLayout></LinearLayout>
2)代码,主代码:
view
plaincopy
to clipboard
package com.myandroid.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
public class MyListView extends Activity {
private ListView listView;
private ImageButton imgbt_sum;
private ListViewAdapter listViewAdapter;
private List<Map<String, Object>> listItems;
private Integer[] imgeIDs = {R.drawable.cake,
R.drawable.gift, R.drawable.letter,
R.drawable.love, R.drawable.mouse,
R.drawable.music};
private String[] goodsNames = {"蛋糕", "礼物",
"邮票", "爱心", "鼠标", "音乐CD"};
private String[] goodsDetails = {
"蛋糕:好好吃。",
"礼物:礼轻情重。",
"邮票:环游世界。",
"爱心:世界都有爱。",
"鼠标:反应敏捷。",
"音乐CD:酷我音乐。"};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView)findViewById(R.id.list_goods);
imgbt_sum = (ImageButton) findViewById(R.id.imgbt_sum);
imgbt_sum.setOnClickListener(new ClickEvent());
listItems = getListItems();
listViewAdapter = new ListViewAdapter(this, listItems); //创建适配器
listView.setAdapter(listViewAdapter);
}
/**
* 初始化商品信息
*/
private List<Map<String, Object>> getListItems() {
List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
for(int i = 0; i < goodsNames.length; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("image", imgeIDs[i]); //图片资源
map.put("title", "物品名称:"); //物品标题
map.put("info", goodsNames[i]); //物品名称
map.put("detail", goodsDetails[i]); //物品详情
listItems.add(map);
}
return listItems;
}
class ClickEvent implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String goodsList = "";
for(int i = 0; i < listItems.size(); i++) {
goodsList += listViewAdapter.hasChecked(i)? goodsNames[i] + " ": "";
}
new AlertDialog.Builder(MyListView.this)
.setTitle("购物清单:")
.setMessage("你好,你选择了如下商品:/n" + goodsList)
.setPositiveButton("确定", null)
.show();
}
}
}
[java] view
plaincopy
package com.myandroid.test;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.ArrayAdapter;import android.widget.ImageButton;import android.widget.ListView;public class MyListView extends Activity {private ListView listView;private ImageButton imgbt_sum;private ListViewAdapter listViewAdapter;private List<Map<String, Object>> listItems;private Integer[] imgeIDs = {R.drawable.cake, R.drawable.gift, R.drawable.letter,R.drawable.love, R.drawable.mouse,R.drawable.music};private String[] goodsNames = {"蛋糕", "礼物", "邮票", "爱心", "鼠标", "音乐CD"};private String[] goodsDetails = {"蛋糕:好好吃。", "礼物:礼轻情重。", "邮票:环游世界。", "爱心:世界都有爱。","鼠标:反应敏捷。","音乐CD:酷我音乐。"}; /* Called when the activity is first created. / @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listView = (ListView)findViewById(R.id.list_goods); imgbt_sum = (ImageButton) findViewById(R.id.imgbt_sum); imgbt_sum.setOnClickListener(new ClickEvent()); listItems = getListItems(); listViewAdapter = new ListViewAdapter(this, listItems); //创建适配器 listView.setAdapter(listViewAdapter); } /* 初始化商品信息 */ private List<Map<String, Object>> getListItems() { List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>(); for(int i = 0; i < goodsNames.length; i++) { Map<String, Object> map = new HashMap<String, Object>(); map.put("image", imgeIDs[i]); //图片资源 map.put("title", "物品名称:"); //物品标题 map.put("info", goodsNames[i]); //物品名称 map.put("detail", goodsDetails[i]); //物品详情 listItems.add(map); } return listItems; } class ClickEvent implements OnClickListener{@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString goodsList = "";for(int i = 0; i < listItems.size(); i++) {goodsList += listViewAdapter.hasChecked(i)? goodsNames[i] + " ": "";}new AlertDialog.Builder(MyListView.this).setTitle("购物清单:").setMessage("你好,你选择了如下商品:/n" + goodsList).setPositiveButton("确定", null).show();} }}
适配器代码:
view
plaincopy
to clipboard
package com.myandroid.test;
import java.util.List;
import java.util.Map;
import android.app.AlertDialog;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class ListViewAdapter extends BaseAdapter {
private Context context; //运行上下文
private List<Map<String, Object>> listItems; //商品信息集合
private LayoutInflater listContainer; //视图容器
private boolean[] hasChecked; //记录商品选中状态
public final class ListItemView{ //自定义控件集合
public ImageView image;
public TextView title;
public TextView info;
public CheckBox check;
public Button detail;
}
public ListViewAdapter(Context context, List<Map<String, Object>> listItems) {
this.context = context;
listContainer = LayoutInflater.from(context); //创建视图容器并设置上下文
this.listItems = listItems;
hasChecked = new boolean[getCount()];
}
public int getCount() {
// TODO Auto-generated method stub
return listItems.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
/**
* 记录勾选了哪个物品
* @param checkedID 选中的物品序号
*/
private void checkedChange(int checkedID) {
hasChecked[checkedID] = !hasChecked[checkedID];
}
/**
* 判断物品是否选择
* @param checkedID 物品序号
* @return 返回是否选中状态
*/
public boolean hasChecked(int checkedID) {
return hasChecked[checkedID];
}
/**
* 显示物品详情
* @param clickID
*/
private void showDetailInfo(int clickID) {
new AlertDialog.Builder(context)
.setTitle("物品详情:" + listItems.get(clickID).get("info"))
.setMessage(listItems.get(clickID).get("detail").toString())
.setPositiveButton("确定", null)
.show();
}
/**
* ListView Item设置
*/
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.e("method", "getView");
final int selectID = position;
//自定义视图
ListItemView listItemView = null;
if (convertView == null) {
listItemView = new ListItemView();
//获取list_item布局文件的视图
convertView = listContainer.inflate(R.layout.list_item, null);
//获取控件对象
listItemView.image = (ImageView)convertView.findViewById(R.id.imageItem);
listItemView.title = (TextView)convertView.findViewById(R.id.titleItem);
listItemView.info = (TextView)convertView.findViewById(R.id.infoItem);
listItemView.detail= (Button)convertView.findViewById(R.id.detailItem);
listItemView.check = (CheckBox)convertView.findViewById(R.id.checkItem);
//设置控件集到convertView
convertView.setTag(listItemView);
}else {
listItemView = (ListItemView)convertView.getTag();
}
// Log.e("image", (String) listItems.get(position).get("title")); //测试
// Log.e("image", (String) listItems.get(position).get("info"));
//设置文字和图片
listItemView.image.setBackgroundResource((Integer) listItems.get(
position).get("image"));
listItemView.title.setText((String) listItems.get(position)
.get("title"));
listItemView.info.setText((String) listItems.get(position).get("info"));
listItemView.detail.setText("商品详情");
//注册按钮点击时间爱你
listItemView.detail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//显示物品详情
showDetailInfo(selectID);
}
});
// 注册多选框状态事件处理
listItemView.check
.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
//记录物品选中状态
checkedChange(selectID);
}
});
return convertView;
}
}