ListView自定义adapter中处理多事件

1.ListView自定义adapter中处理多事件


使用过ListView 的开发人员都知道,ListView 在一般情况下只能对每条记录设置一个监听事件。如果想在其中添加多个事件,就需要自定义Adapter 。

 

下面介绍一下如何自定义adapter 以及如何在一个Item 中绑定多个事件。

这里我们需要两个XML 文件、两个java 类。分别是存放ListView 的XML 、ListViewItem 的XML 、Activity 类和Adapter 类。

 

首先说说两个XML 文件。

main.xml

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:padding"10dip"   
  6.     android:orientation="vertical" >  
  7.   
  8.     <ListView   
  9.         android:id="@id/android:list"   
  10.         android:layout_width = "fill_parent"   
  11.         android:layout_height = "fill_parent" />   
  12.   
  13. </LinearLayout>  

 

注意:这里的ListView 中id 使用了android 自定义的: @id/android:list

 

lvItem.xml

 

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:descendantFocusability="blocksDescendants"  
  6.     android:padding="5dip" >  
  7.   
  8.     <ImageView  
  9.         android:id="@+id/ItemImage"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:padding="5dip" />  
  13.   
  14.     <ImageButton  
  15.         android:id="@+id/ItemCloseWin"  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content"  
  18.         android:layout_alignBottom="@+id/ItemWinName"  
  19.         android:layout_alignTop="@+id/ItemWinName"  
  20.         android:layout_alignParentRight="true"  
  21.         android:background="#e0000000"  
  22.         android:focusable="false"  
  23.         android:gravity="left|center_vertical"  
  24.         android:src="@android:drawable/ic_menu_close_clear_cancel" />  
  25.   
  26.     <ImageButton   
  27.         android:id="@+id/ItemEmail"  
  28.         android:layout_width="wrap_content"  
  29.         android:layout_height="wrap_content"  
  30.         android:layout_alignBottom="@id/ItemWinName"  
  31.         android:layout_alignTop="@id/ItemWinName"  
  32.         android:layout_toLeftOf="@id/ItemCloseWin"  
  33.         android:background="#e0000000"  
  34.         android:focusable="false"  
  35.         android:gravity="left|center_vertical"  
  36.         android:src="@android:drawable/ic_dialog_email" />  
  37.       
  38.     <TextView  
  39.         android:id="@+id/ItemWinName"  
  40.         android:layout_width="wrap_content"  
  41.         android:layout_height="wrap_content"  
  42.         android:layout_alignBottom="@id/ItemImage"  
  43.         android:layout_alignTop="@id/ItemImage"  
  44.         android:layout_toLeftOf="@id/ItemEmail"  
  45.         android:layout_toRightOf="@id/ItemImage"  
  46.         android:gravity="left|center_vertical"  
  47.         android:text="title"  
  48.         android:textSize="20dip" />  
  49.   
  50. </RelativeLayout>  

 

 

接下来看看Activity

 

Java代码   收藏代码
  1. package cn.mutil;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5.   
  6. import android.app.ListActivity;  
  7. import android.os.Bundle;  
  8. import android.view.View;  
  9. import android.widget.AdapterView;  
  10. import android.widget.AdapterView.OnItemClickListener;  
  11. import android.widget.ListView;  
  12. import android.widget.TextView;  
  13. import android.widget.Toast;  
  14. /** 
  15.  * ListView item 多事件Activity 
  16.  * @author lihua 
  17.  * 
  18.  */  
  19. public class LvWithButtonActivity extends ListActivity {  
  20.   
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.main);  
  25.   
  26.         // 关联Layout中的ListView  
  27.         ListView vncListView = (ListView) findViewById(android.R.id.list);  
  28.   
  29.         // 生成动态数组,加入数据  
  30.         ArrayList<HashMap<String, Object>> remoteWindowItem = new ArrayList<HashMap<String, Object>>();  
  31.         for (int i = 0; i < 10; i++) {  
  32.             HashMap<String, Object> map = new HashMap<String, Object>();  
  33.             map.put("ItemImage", R.drawable.ic_launcher); // 图像资源的ID  
  34.             map.put("ItemWinName""Window ID " + i);  
  35.             map.put("ItemEmail", android.R.drawable.ic_dialog_email);  
  36.             map.put("ItemCloseWin", android.R.drawable.ic_menu_close_clear_cancel);  
  37.             remoteWindowItem.add(map);  
  38.         }  
  39.   
  40.         // 生成适配器的Item和动态数组对应的元素  
  41.         LvButtonAdapter listItemAdapter = new LvButtonAdapter(this,  
  42.                 remoteWindowItem, // 数据源  
  43.                 R.layout.lvitem, // ListItem对应的XML  
  44.                 // 动态数组与ImageItem对应的子项  
  45.                 new String[] { "ItemImage""ItemWinName","ItemEmail""ItemCloseWin" },  
  46.                 // ImageItem的XML文件里面的一个ImageView,两个TextView ID  
  47.                 new int[] { R.id.ItemImage, R.id.ItemWinName, R.id.ItemEmail, R.id.ItemCloseWin });  
  48.   
  49.         vncListView.setAdapter(listItemAdapter);  
  50.           
  51.         /** 
  52.          * 设置整个Item被点击的事件 
  53.          * 该事件在其他有事件的组件未被点击时触发 
  54.          */  
  55.         vncListView.setOnItemClickListener(new OnItemClickListener() {  
  56.   
  57.             @Override  
  58.             public void onItemClick(AdapterView<?> adapter, View view,   
  59.                     int position,long arg3) {  
  60.                   
  61.                 TextView content = (TextView)view.findViewById(R.id.ItemWinName);  
  62.                 Toast.makeText(LvWithButtonActivity.this, content.getText().toString() , Toast.LENGTH_SHORT).show();  
  63.             }  
  64.               
  65.         });  
  66.     }  
  67.   
  68.     @Override  
  69.     protected void onListItemClick(ListView l, View v, int position, long id) {  
  70.         super.onListItemClick(l, v, position, id);  
  71.         l.getItemAtPosition(position);  
  72.     }  
  73.   
  74. }  

 

最后一个也是最重要的一个,自定义adapter

 

Java代码   收藏代码
  1. package cn.mutil;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6.   
  7. import android.content.Context;  
  8. import android.view.LayoutInflater;  
  9. import android.view.View;  
  10. import android.view.ViewGroup;  
  11. import android.widget.BaseAdapter;  
  12. import android.widget.ImageButton;  
  13. import android.widget.ImageView;  
  14. import android.widget.TextView;  
  15. import android.widget.Toast;  
  16.   
  17. public class LvButtonAdapter extends BaseAdapter {  
  18.   
  19.     private class ButtonViewHolder {  
  20.         ImageView appIcon;  
  21.         TextView appName;  
  22.         ImageButton buttonEmail;  
  23.         ImageButton buttonClose;  
  24.     }  
  25.   
  26.     private ArrayList<HashMap<String, Object>> mAppList;//用于存放传递过来显示于ListView中的 数据  
  27.     private LayoutInflater mInflater;  
  28.     private Context mContext;  
  29.     private String[] keyString;  
  30.     private int[] valueViewID;  
  31.     private ButtonViewHolder holder;  
  32.   
  33.     public LvButtonAdapter(Context c,//上下文  
  34.             ArrayList<HashMap<String, Object>> appList,//绑定数据   
  35.             int resource00000,//ListView行记录layout  
  36.             String[] from,   
  37.             int[] to) {  
  38.         mAppList = appList;  
  39.         mContext = c;  
  40.         mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  41.         keyString = new String[from.length];  
  42.         valueViewID = new int[to.length];  
  43.         System.arraycopy(from, 0, keyString, 0, from.length);  
  44.         System.arraycopy(to, 0, valueViewID, 0, to.length);  
  45.     }  
  46.   
  47.     @Override  
  48.     public int getCount() {  
  49.         return mAppList.size();  
  50.     }  
  51.   
  52.     @Override  
  53.     public Object getItem(int position) {  
  54.         return mAppList.get(position);  
  55.     }  
  56.   
  57.     @Override  
  58.     public long getItemId(int position) {  
  59.         return position;  
  60.     }  
  61.     /** 
  62.      * 删除数据集中的值 
  63.      * @param position 
  64.      */  
  65.     public void removeItem(int position) {  
  66.         mAppList.remove(position);  
  67.         this.notifyDataSetChanged();  
  68.     }  
  69.       
  70.     /** 
  71.      * 改变数据集中的值 
  72.      * @param position 
  73.      * @param map 
  74.      */  
  75.     public void changeItem(int position,HashMap<String, Object> map){  
  76.         mAppList.remove(position);  
  77.         mAppList.add(position, map);  
  78.         this.notifyDataSetChanged();  
  79.     }  
  80.   
  81.     @Override  
  82.     public View getView(int position, View convertView, ViewGroup parent) {  
  83.         if (convertView != null) {  
  84.             holder = (ButtonViewHolder) convertView.getTag();  
  85.         } else {  
  86.             convertView = mInflater.inflate(R.layout.lvitem, null);  
  87.             holder = new ButtonViewHolder();  
  88.             holder.appIcon = (ImageView) convertView  
  89.                     .findViewById(valueViewID[0]);//可以将valueViewID[0]替换成R.id.xxx  
  90.             holder.appName = (TextView) convertView  
  91.                     .findViewById(valueViewID[1]);  
  92.             holder.buttonEmail = (ImageButton) convertView  
  93.                     .findViewById(valueViewID[2]);  
  94.             holder.buttonClose = (ImageButton) convertView  
  95.                     .findViewById(valueViewID[3]);  
  96.             convertView.setTag(holder);  
  97.         }  
  98.   
  99.         HashMap<String, Object> appInfo = mAppList.get(position);  
  100.         if (appInfo != null) {  
  101.             String aname = (String) appInfo.get(keyString[1]);  
  102.             int mid = (Integer) appInfo.get(keyString[0]);  
  103.             int eid = (Integer) appInfo.get(keyString[2]);  
  104.             int bid = (Integer) appInfo.get(keyString[3]);  
  105.               
  106.             holder.appName.setText(aname);  
  107.             holder.appName.setOnClickListener(new LvButtonListener(position));  
  108.             holder.appIcon.setImageDrawable(holder.appIcon.getResources().getDrawable(mid));              
  109.             holder.buttonEmail.setImageDrawable(holder.buttonEmail.getResources().getDrawable(eid));  
  110.             holder.buttonEmail.setOnClickListener(new LvButtonListener(position));            
  111.             holder.buttonClose.setImageDrawable(holder.buttonClose.getResources().getDrawable(bid));  
  112.             holder.buttonClose.setOnClickListener(new LvButtonListener(position));  
  113.         }  
  114.         return convertView;  
  115.     }  
  116.       
  117.     /** 
  118.      * 按钮事件监听 
  119.      * @author lihua 
  120.      * 
  121.      */  
  122.     private class LvButtonListener implements View.OnClickListener {  
  123.         private int position;  
  124.   
  125.         LvButtonListener(int pos) {  
  126.             position = pos;  
  127.         }  
  128.   
  129.         @Override  
  130.         public void onClick(View v) {  
  131.             int vid = v.getId();  
  132.               
  133.             HashMap<String, Object> curMap = (HashMap<String, Object>)getItem(position);          
  134.               
  135.             if (vid == holder.buttonClose.getId()){ //删除一行记录  
  136.                   
  137.                 Toast.makeText(mContext,"position:"+position+",data is being Deleted", Toast.LENGTH_LONG).show();  
  138.                 removeItem(position);  
  139.                 //可以在这里操作数据库或更新服务端数据  
  140.                   
  141.             }else if(vid == holder.buttonEmail.getId()){//发送邮件  
  142.                   
  143.                 Toast.makeText(mContext, "position:"+position+",sending email to xxx!",   
  144.                         Toast.LENGTH_SHORT).show();  
  145.                 //可以在这里操作数据库或更新服务端数据  
  146.                   
  147.             }else if(vid == holder.appName.getId()){//设置名称  
  148.                   
  149.                 Toast.makeText(mContext, "position is "+position+", appName:"+curMap.get("ItemWinName").toString(),   
  150.                         Toast.LENGTH_SHORT).show();  
  151.                 curMap.put("ItemWinName", System.currentTimeMillis()+"");  
  152.                 changeItem(position,curMap);  
  153.                 //可以在这里操作数据库或更新服务端数据  
  154.                   
  155.             }  
  156.         }  
  157.     }  
  158.   
  159. }  


2.用ViewHolder,对ListView进行一些性能优化




最近写Adapter写得多了,慢慢就熟悉了。

  用ViewHolder,主要是进行一些性能优化,减少一些不必要的重复操作。(WXD同学教我的。)

  具体不分析了,直接上一份代码吧:

复制代码
public class MarkerItemAdapter extends BaseAdapter
{
    private Context mContext = null;
    private List<MarkerItem> mMarkerData = null;

    public MarkerItemAdapter(Context context, List<MarkerItem> markerItems)
    {
        mContext = context;
        mMarkerData = markerItems;
    }

    public void setMarkerData(List<MarkerItem> markerItems)
    {
        mMarkerData = markerItems;
    }

    @Override
    public int getCount()
    {
        int count = 0;
        if (null != mMarkerData)
        {
            count = mMarkerData.size();
        }
        return count;
    }

    @Override
    public MarkerItem getItem(int position)
    {
        MarkerItem item = null;

        if (null != mMarkerData)
        {
            item = mMarkerData.get(position);
        }

        return item;
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ViewHolder viewHolder = null;
        if (null == convertView)
        {
            viewHolder = new ViewHolder();
            LayoutInflater mInflater = LayoutInflater.from(mContext);
            convertView = mInflater.inflate(R.layout.item_marker_item, null);

            viewHolder.name = (TextView) convertView.findViewById(R.id.name);
            viewHolder.description = (TextView) convertView
                    .findViewById(R.id.description);
            viewHolder.createTime = (TextView) convertView
                    .findViewById(R.id.createTime);

            convertView.setTag(viewHolder);
        }
        else
        {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        // set item values to the viewHolder:

        MarkerItem markerItem = getItem(position);
        if (null != markerItem)
        {
            viewHolder.name.setText(markerItem.getName());
            viewHolder.description.setText(markerItem.getDescription());
            viewHolder.createTime.setText(markerItem.getCreateDate());
        }

        return convertView;
    }

    private static class ViewHolder
    {
        TextView name;
        TextView description;
        TextView createTime;
    }

}
复制代码

 

  其中MarkerItem是自定义的类,其中包含name,description,createTime等字段,并且有相应的get和set方法。

 

  ViewHolder是一个内部类,其中包含了单个项目布局中的各个控件。

  单个项目的布局,即R.layout.item_marker_item如下:

复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:padding="5dp">

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Description"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/createTime"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="CreateTime"
        android:textSize="16sp" />

</LinearLayout>
复制代码

 

官方的API Demos中也有这个例子:

package com.example.android.apis.view中的List14:

复制代码
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.apis.view;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.ImageView;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import com.example.android.apis.R;

/**
 * Demonstrates how to write an efficient list adapter. The adapter used in this example binds
 * to an ImageView and to a TextView for each row in the list.
 *
 * To work efficiently the adapter implemented here uses two techniques:
 * - It reuses the convertView passed to getView() to avoid inflating View when it is not necessary
 * - It uses the ViewHolder pattern to avoid calling findViewById() when it is not necessary
 *
 * The ViewHolder pattern consists in storing a data structure in the tag of the view returned by
 * getView(). This data structures contains references to the views we want to bind data to, thus
 * avoiding calls to findViewById() every time getView() is invoked.
 */
public class List14 extends ListActivity {

    private static class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private Bitmap mIcon1;
        private Bitmap mIcon2;

        public EfficientAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);

            // Icons bound to the rows.
            mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_1);
            mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_2);
        }

        /**
         * The number of items in the list is determined by the number of speeches
         * in our array.
         *
         * @see android.widget.ListAdapter#getCount()
         */
        public int getCount() {
            return DATA.length;
        }

        /**
         * Since the data comes from an array, just returning the index is
         * sufficent to get at the data. If we were using a more complex data
         * structure, we would return whatever object represents one row in the
         * list.
         *
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position) {
            return position;
        }

        /**
         * Use the array index as a unique id.
         *
         * @see android.widget.ListAdapter#getItemId(int)
         */
        public long getItemId(int position) {
            return position;
        }

        /**
         * Make a view to hold each row.
         *
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls
            // to findViewById() on each row.
            ViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is no need
            // to reinflate it. We only inflate a new View when the convertView supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.list_item_icon_text, null);

                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.text);
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);

                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }

            // Bind the data efficiently with the holder.
            holder.text.setText(DATA[position]);
            holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);

            return convertView;
        }

        static class ViewHolder {
            TextView text;
            ImageView icon;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new EfficientAdapter(this));
    }

    private static final String[] DATA = Cheeses.sCheeseStrings;
}
复制代码

   其中布局:

 

复制代码
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView android:id="@+id/icon"
        android:layout_width="48dip"
        android:layout_height="48dip" />

    <TextView android:id="@+id/text"
        android:layout_gravity="center_vertical"
        android:layout_width="0dip"
        android:layout_weight="1.0"
        android:layout_height="wrap_content" />

</LinearLayout>
复制代码



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值