1. 程式人生 > >listView中Button點選事件和介面的寫法

listView中Button點選事件和介面的寫法

複製程式碼
 1 package com.ivan.adapter;
 2 
 3 import java.util.List;
 4 
 5 import android.content.Context;
 6 import android.util.Log;
 7 import android.view.LayoutInflater;
 8 import android.view.View;
 9 import android.view.View.OnClickListener;
10 import android.view.ViewGroup;
11 import android.widget.BaseAdapter;
12 import android.widget.Button; 13 import android.widget.TextView; 14 15 import com.ivan.listvieweventabstract.R; 16 17 public class ContentAdapter extends BaseAdapter { 18 19 private static final String TAG = "ContentAdapter"; 20 private List<String> mContentList; 21 private LayoutInflater mInflater;
22 private MyClickListener mListener; 23 24 public ContentAdapter(Context context, List<String> contentList, 25 MyClickListener listener) { 26 mContentList = contentList; 27 mInflater = LayoutInflater.from(context); 28 mListener = listener; 29 }
30 31 @Override 32 public int getCount() { 33 Log.i(TAG, "getCount"); 34 return mContentList.size(); 35 } 36 37 @Override 38 public Object getItem(int position) { 39 Log.i(TAG, "getItem"); 40 return mContentList.get(position); 41 } 42 43 @Override 44 public long getItemId(int position) { 45 Log.i(TAG, "getItemId"); 46 return position; 47 } 48 49 @Override 50 public View getView(int position, View convertView, ViewGroup parent) { 51 Log.i(TAG, "getView"); 52 ViewHolder holder = null; 53 if (convertView == null) { 54 convertView = mInflater.inflate(R.layout.list_item, null); 55 holder = new ViewHolder(); 56 holder.textView = (TextView) convertView 57 .findViewById(R.id.textView1); 58 holder.button = (Button) convertView.findViewById(R.id.button1); 59 convertView.setTag(holder); 60 } else { 61 holder = (ViewHolder) convertView.getTag(); 62 } 63 holder.textView.setText(mContentList.get(position)); 64 holder.button.setOnClickListener(mListener); 65 holder.button.setTag(position); 66 return convertView; 67 } 68 69 public class ViewHolder { 70 public TextView textView; 71 public Button button; 72 } 73 74 /** 75 * 用於回撥的抽象類 76 * @author Ivan Xu 77 * 2014-11-26 78 */ 79 public static abstract class MyClickListener implements OnClickListener { 80 /** 81 * 基類的onClick方法 82 */ 83 @Override 84 public void onClick(View v) { 85 myOnClick((Integer) v.getTag(), v); 86 } 87 public abstract void myOnClick(int position, View v); 88 } 89 }
複製程式碼