首先,给出自定义OnClickListener代码:
/* * 自定义的OnClickListener,提供给外部容器(Activity/Fragment 回调使用) */ public interface showMessageItemOnClickListener extends OnClickListener{ /** * * @param viewID listview 中 item 内部组件的标记,可以使用R.id.xxx 作为标记,用于区分具体点击的组件 * @param position listview 中 item 的序号,用于区分点击组件所在的item */ public void onClick(int viewID ,int position); }
再来给出ListView Adapter代码:
public class ShowMessageAdapter extends BaseAdapter{ private Context context ; private List<ShowMessage> data ; private showMessageItemOnClickListener onClickListener ; public ShowMessageAdapter(Context context ,List<ShowMessage> data ,showMessageItemOnClickListener onClickListener) { super(); this.data = data ; this.context = context ; this.onClickListener = onClickListener ;//由外部容器传入(Activity/Fragment) } @Override public int getCount() { return data==null?0:data.size() ; } @Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int arg0) { return 0; } @Override public View getView(final int position, View arg1, ViewGroup viewGroup) { OnClickListener onClickListener = new OnClickListener() { @Override public void onClick(View view) { switch (view.getId()) { case R.id.message_layout_iv_comment: ShowMessageAdapter.this.onClickListener.onClick(view.getId(), position) ; break; default: break; } } }; View rootView = LayoutInflater.from(context).inflate(R.layout.message_layout, null) ; ImageView imageView = (ImageView) rootView.findViewById(R.id.message_layout_iv_comment); imageView.setOnClickListener(onClickListener) ; return rootView; } }
通过getView(),内部实现的OnClickListener,调用外部容器出入的接口,传入itemPosition和ViewID参数,实现定位点击事件监听.
再来给出外部容器代码:
public class HomeFragment extends Fragment implements showMessageItemOnClickListener{ //省略中间代码 @Override public void onClick(int viewID, int position) { // TODO Auto-generated method stub switch (viewID) { case R.id.message_layout_iv_comment: Toast.makeText(getActivity(), "position"+position, Toast.LENGTH_SHORT).show() ; break; default: break; } } }