在Activity或Fragment中响应ListView内部按钮的点击事件

在做项目时,遇到点击ListView内部按钮的事件,感觉应在Adapter中写响应事件,但总感觉怪怪的,后来去网上搜索资料,大牛们给出合理的操作:在Adapter中定义一个回调接口,在Activity中实现该接口,从而实现对点击事件的响应。除了接口回调之外,也可以使用抽象类回调

1.接口回调。

Adapter中代码:

package com.net.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

import com.net.R;
import com.net.beans.UserBean;

public class ContactAddAdapter extends BaseAdapter implements OnClickListener{
	private List mList;
	private Context mContext;
	private LayoutInflater mInflater;
	private MyClickListener mListener;//所有listview的item共用同一个
	
	//自定义接口,用于回调按钮点击事件到Activity
	public interface MyClickListener{
		public void clickListener(View v);
	}
	
	public ContactAddAdapter(Context context,List userBeansList,MyClickListener listener) {
		// TODO Auto-generated constructor stub
		mList = userBeansList;
		mContext = context;
		mInflater = LayoutInflater.from(context);
		mListener = listener;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}
	ViewHolder holder=null ;
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		if(convertView == null){
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.item_addfriend_listview, null);
			holder.tvName = (TextView) convertView.findViewById(R.id.tv_addfriends);
			holder.tbAddFriends = (ImageButton) convertView.findViewById(R.id.ib_addfriends);
			convertView.setTag(holder);
		}else{
			holder = (ViewHolder) convertView.getTag();
		}
		holder.tvName.setText(mList.get(position).userName);
		
		holder.tbAddFriends.setOnClickListener(this);
		holder.tbAddFriends.setTag(position);//不设置setTag会导致空指针异常
		return convertView;
	}
	class ViewHolder{
		public TextView tvName;
		public ImageButton tbAddFriends;
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		mListener.clickListener(v);
		
	}

}
Activity中代码:

public class ContactAddPage extends Fragment implements MyClickListener{
	final static String SERVICE_NS = "http://test.org/";
	final static String SERVICE_URL = "http://192.168.56.1:8080/WebService2.asmx?WSDL";
	private View view;
	private ListView mListView;
	private String name,friendname;
	List userBeansList = new ArrayList();
	private Handler handler;

	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		view=inflater.inflate(R.layout.contact_addfriend, null);
		
		new NewsAsyncTask().execute(SERVICE_URL);	
		
		initView();
		
		handler = new Handler(){
			public void handleMessage(Message msg){
				if(msg.what == X0){
					Toast.makeText(getActivity(), "添加失败", Toast.LENGTH_SHORT).show();
				}
				else if(msg.what == X1){
					Toast.makeText(getActivity(), "添加好友成功", Toast.LENGTH_SHORT).show();
				}
				
			}
		};
		return view;
	}

	private void initView() {
		// TODO Auto-generated method stub
		mListView = (ListView) view.findViewById(R.id.list_friend);
	}
	/**
	 * 实现网络的异步访问
	 * @author Administrator
	 *
	 */
	class NewsAsyncTask extends AsyncTask>{
		
		@Override
		protected List doInBackground(String... param) {
			return getData(param[0]); 
		}
		protected void onPostExecute(List result) {
			super.onPostExecute(result);
			
			ContactAddAdapter adapter = new ContactAddAdapter(getActivity(),userBeansList, ContactAddPage.this);//Fragment中,Activity中第一个可以用this
			mListView.setAdapter(adapter);
		}	
	}
	/**
	 * 将URL对应的json格式数据转化为我们封装的Bean对象
	 * @param url
	 * @return
	 */
	private List getData(String url) {
		String methodName = "Friend";
		final HttpTransportSE ht = new HttpTransportSE(url);
		final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		//实例化
		SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);
		//设置调用方法的参数值
		soapObject.addPropertyIfValue("user", name);
		envelope.bodyOut = soapObject;
		// c#写的应用程序必须加上这句
		envelope.dotNet = true;
		try {
			System.out.println("start soap");
			ht.call(null, envelope);
			System.out.println("start call");
			if (envelope.getResponse()!=null) {
				SoapObject result = (SoapObject)envelope.bodyIn;
				SoapObject detail = (SoapObject) result.getProperty(0);
			      int count = detail.getPropertyCount();  
			      System.out.println("count="+count);
			      UserBean mBeans=null;
			      for (int i = 0; i < count; i++) {  
			    	  mBeans= new UserBean();
			    	mBeans.userName=detail.getProperty(i).toString();
			    	
			    	System.out.println(mBeans.userName);
			    	userBeansList.add(mBeans);
			      } 
			 
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userBeansList;
	}
	/**
	 * 接口方法,响应ListView按钮点击事件
         */
	@Override
	public void clickListener(View v) {
		// TODO Auto-generated method stub
		 Toast.makeText(
                 getActivity(),"listview的内部的按钮被点击了!,位置是" + (Integer) v.getTag() + ",内容是-->"+ userBeansList.get((Integer) v.getTag()).userName,
                 Toast.LENGTH_SHORT).show();
		 
	
	}
}
2.使用抽象类回调

Adapter代码:

package com.ivan.adapter;

import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.ivan.listvieweventabstract.R;

public class ContentAdapter extends BaseAdapter {

    private static final String TAG = "ContentAdapter";
    private List mContentList;
    private LayoutInflater mInflater;
    private MyClickListener mListener;

    public ContentAdapter(Context context, List contentList,
            MyClickListener listener) {
        mContentList = contentList;
        mInflater = LayoutInflater.from(context);
        mListener = listener;
    }

    @Override
    public int getCount() {
        Log.i(TAG, "getCount");
        return mContentList.size();
    }

    @Override
    public Object getItem(int position) {
        Log.i(TAG, "getItem");
        return mContentList.get(position);
    }

    @Override
    public long getItemId(int position) {
        Log.i(TAG, "getItemId");
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Log.i(TAG, "getView");
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, null);
            holder = new ViewHolder();
            holder.textView = (TextView) convertView
                    .findViewById(R.id.textView1);
            holder.button = (Button) convertView.findViewById(R.id.button1);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.textView.setText(mContentList.get(position));
        holder.button.setOnClickListener(mListener);
        holder.button.setTag(position);
        return convertView;
    }

    public class ViewHolder {
        public TextView textView;
        public Button button;
    }

    /**
     * 用于回调的抽象类
     * @author Ivan Xu
     * 2014-11-26
     */
    public static abstract class MyClickListener implements OnClickListener {
        /**
         * 基类的onClick方法
         */
        @Override
        public void onClick(View v) {
            myOnClick((Integer) v.getTag(), v);
        }
        public abstract void myOnClick(int position, View v);
    }
}

Activity代码:

package com.ivan.listvieweventdemo;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.ivan.adapter.ContentAdapter;
import com.ivan.adapter.ContentAdapter.MyClickListener;
import com.ivan.listvieweventabstract.R;

public class MainActivity extends Activity implements OnItemClickListener {

    // 模拟listview中加载的数据
    private static final String[] CONTENTS = { "北京", "上海", "广州", "深圳", "苏州",
            "南京", "武汉", "长沙", "杭州" };
    private List contentList;
    private ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    private void init() {
        mListView = (ListView) findViewById(R.id.listview);
        contentList = new ArrayList();
        for (int i = 0; i < CONTENTS.length; i++) {
            contentList.add(CONTENTS[i]);
        }
        //实例化ContentAdapter类,并传入实现类
        mListView.setAdapter(new ContentAdapter(this, contentList, mListener));
        
        mListView.setOnItemClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    //响应item点击事件
    @Override
    public void onItemClick(AdapterView arg0, View v, int position, long id) {
        Toast.makeText(this, "listview的item被点击了!,点击的位置是-->" + position,
                Toast.LENGTH_SHORT).show();
    }

    /**
     * 实现类,响应按钮点击事件
     */
    private MyClickListener mListener = new MyClickListener() {
        @Override
        public void myOnClick(int position, View v) {
            Toast.makeText(
                    MainActivity.this,
                    "listview的内部的按钮被点击了!,位置是-->" + position + ",内容是-->"
                            + contentList.get(position), Toast.LENGTH_SHORT)
                    .show();
        }
    };
}


你可能感兴趣的:(Android)