«

自定义ListView适配器继承BaseAdapter

时间:2024-3-2 17:59     作者:韩俊     分类: Android


在开发中,我们经常使用到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&quot;
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

&lt;!-- 结算 --&gt;  
&lt;LinearLayout android:gravity=&quot;center_horizontal&quot;  
android:orientation=&quot;horizontal&quot; android:layout_width=&quot;fill_parent&quot;  
android:layout_height=&quot;wrap_content&quot;&gt;  
&lt;TextView android:text=&quot;结算: &quot;  
    android:layout_width=&quot;wrap_content&quot;  
    android:layout_height=&quot;wrap_content&quot;   
    android:textColor=&quot;#FFFFFFFF&quot;   
    android:textSize=&quot;20px&quot;/&gt;  
&lt;ImageButton android:id=&quot;@&#43;id/imgbt_sum&quot;   
    android:layout_width=&quot;40px&quot;  
    android:layout_height=&quot;40px&quot;  
    android:background = &quot;@drawable/shopping&quot; /&gt;  
&lt;/LinearLayout&gt;  

&lt;TextView android:text=&quot;商品列表: &quot;  
    android:layout_width=&quot;wrap_content&quot;  
    android:layout_height=&quot;wrap_content&quot;   
    android:textColor=&quot;#FFFFFFFF&quot; /&gt;  

&lt;!-- 商品列表 --&gt;   
&lt;ListView android:id=&quot;@&#43;id/list_goods&quot;   
    android:layout_width=&quot;fill_parent&quot;  
    android:layout_height=&quot;wrap_content&quot; /&gt;  

</LinearLayout>

[xhtml] view
plaincopy

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android&quot; 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&quot;
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">

&lt;!-- 商品图片 --&gt;  
&lt;ImageView android:id=&quot;@&#43;id/imageItem&quot;   
    android:layout_width=&quot;wrap_content&quot;  
    android:layout_height=&quot;wrap_content&quot;   
    android:layout_margin=&quot;5px&quot;/&gt;  

&lt;!-- 商品信息 --&gt;  
&lt;LinearLayout android:orientation=&quot;vertical&quot;  
    android:layout_width=&quot;wrap_content&quot;   
    android:layout_height=&quot;wrap_content&quot;&gt;  

    &lt;TextView android:id=&quot;@&#43;id/titleItem&quot;   
        android:layout_width=&quot;wrap_content&quot;  
        android:layout_height=&quot;wrap_content&quot;   
        android:textColor=&quot;#FFFFFFFF&quot;  
        android:textSize=&quot;13px&quot; /&gt;  
    &lt;TextView android:id=&quot;@&#43;id/infoItem&quot;   
        android:layout_width=&quot;wrap_content&quot;  
        android:layout_height=&quot;wrap_content&quot;   
        android:textColor=&quot;#FFFFFFFF&quot;  
        android:textSize=&quot;22px&quot; /&gt;  
&lt;/LinearLayout&gt;  

&lt;!-- 购买和商品详情 --&gt;  
&lt;LinearLayout android:gravity=&quot;right&quot;  
android:orientation=&quot;horizontal&quot; android:layout_width=&quot;fill_parent&quot;  
android:layout_height=&quot;wrap_content&quot;&gt;  
&lt;CheckBox android:id=&quot;@&#43;id/checkItem&quot;   
    android:layout_width=&quot;wrap_content&quot;  
    android:layout_height=&quot;wrap_content&quot;   
    android:layout_margin=&quot;5px&quot;/&gt;  
&lt;Button  android:id=&quot;@&#43;id/detailItem&quot;   
    android:layout_width=&quot;wrap_content&quot;  
    android:layout_height=&quot;wrap_content&quot;   
    android:layout_margin=&quot;5px&quot;/&gt;  
&lt;/LinearLayout&gt;  

</LinearLayout>

[xhtml] view
plaincopy

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android&quot;android:orientation=&quot;horizontal&quot; 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&lt;Map&lt;String, Object&gt;&gt; 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 = {&quot;蛋糕&quot;, &quot;&#31036;物&quot;,   
        &quot;邮票&quot;, &quot;爱心&quot;, &quot;鼠标&quot;, &quot;音乐CD&quot;};  
private String[] goodsDetails = {  
        &quot;蛋糕:好好吃。&quot;,   
        &quot;&#31036;物:&#31036;轻情重。&quot;,   
        &quot;邮票:环游世界。&quot;,   
        &quot;爱心:世界都有爱。&quot;,  
        &quot;鼠标:反应敏捷。&quot;,  
        &quot;音乐CD:酷我音乐。&quot;};  

/** 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&lt;Map&lt;String, Object&gt;&gt; getListItems() {  
    List&lt;Map&lt;String, Object&gt;&gt; listItems = new ArrayList&lt;Map&lt;String, Object&gt;&gt;();  
    for(int i = 0; i &lt; goodsNames.length; i&#43;&#43;) {  
        Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();   
        map.put(&quot;image&quot;, imgeIDs[i]);               //图片资源   
        map.put(&quot;title&quot;, &quot;物品名称:&quot;);              //物品标题   
        map.put(&quot;info&quot;, goodsNames[i]);     //物品名称   
        map.put(&quot;detail&quot;, goodsDetails[i]); //物品详情   
        listItems.add(map);  
    }     
    return listItems;  
}  

class ClickEvent implements OnClickListener{  

    @Override  
    public void onClick(View v) {  
        // TODO Auto-generated method stub   
        String goodsList = &quot;&quot;;  
        for(int i = 0; i &lt; listItems.size(); i&#43;&#43;) {  
            goodsList &#43;= listViewAdapter.hasChecked(i)? goodsNames[i] &#43; &quot;  &quot;: &quot;&quot;;  
        }  
        new AlertDialog.Builder(MyListView.this)  
        .setTitle(&quot;购物清单:&quot;)  
        .setMessage(&quot;你好,你选择了如下商品:/n&quot; &#43; goodsList)  
        .setPositiveButton(&quot;确定&quot;, 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&lt;Map&lt;String, Object&gt;&gt; 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(&quot;物品详情:&quot; &#43; listItems.get(clickID).get(&quot;info&quot;))  
    .setMessage(listItems.get(clickID).get(&quot;detail&quot;).toString())                
    .setPositiveButton(&quot;确定&quot;, null)  
    .show();  
}  

/** 
 * ListView Item设置 
 */  
public View getView(int position, View convertView, ViewGroup parent) {  
    // TODO Auto-generated method stub   
    Log.e(&quot;method&quot;, &quot;getView&quot;);  
    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(&quot;image&quot;));  
    listItemView.title.setText((String) listItems.get(position)  
            .get(&quot;title&quot;));  
    listItemView.info.setText((String) listItems.get(position).get(&quot;info&quot;));  
    listItemView.detail.setText(&quot;商品详情&quot;);  
    //注册按钮点击时间爱你   
    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;  
}  

}

标签: android

热门推荐