要為ListView添加Item的點擊事件酷宵,需要在adapter為每個Item設(shè)置點擊事件膛腐,然后暴露給外部adapter調(diào)用铡俐,給ListView注冊監(jiān)聽事件结蟋。具體代碼:
public class ListViewAdapter extends ArrayAdapter<Book> implements View.OnClickListener{
private int resourceID;
private OnListViewOnClickedListener mOnItemClickListener = null;
public ListViewAdapter(Context context, int resource ,List<Book> objects) {
super(context, resource, objects);
resourceID = resource;
}
public static interface OnListViewOnClickedListener {
void onItemClick(View view , String data);
}
@Override
public View getView(int position,View convertView,ViewGroup parent) {
Book book = getItem(position);
View view = LayoutInflater.from(getContext()).inflate(resourceID, parent, false);
TextView title = (TextView) view.findViewById(R.id.list_item_title);
TextView info = (TextView) view.findViewById(R.id.list_item_info);
title.setText(book.getTitle());
info.setText(book.getInfo());
// 給每個item注冊點擊事件
view.setOnClickListener(this);
return view;
}
@Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
// 這里使用getTag方法獲取數(shù)據(jù)
mOnItemClickListener.onItemClick(view,(String) view.getTag());
}
}
public void setOnItemClickListener(OnListViewOnClickedListener listener) {
// 獲取得到的listener
this.mOnItemClickListener = listener;
}
}