在Andoird中,当activity中需要处理adapter中ListView/或者其他列表的item点击事件,这时候需要用到回调接口。
方式:在Adapter中定义的接口(相当于发布),在activity中实现Adapter中定义的接口(相当于是响应)。
这样activity中便能轻松获取adapter中的数据:
①回调接口可以把adapter中处理过的数据传给activity。
②Activity中获取item中数据可以直接用 adapter.getItem(position)获取,也可以直接在activity获取到的数据中获取
Adapter中
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
final ViewHolder viewHolder;
if (convertView == null) {
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
setAction(viewHolder.action_button, position,);
return convertView;
}
private void setAction(final View view,final int position)
{
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(onItemPlayClick != null) {
onItemPlayClick.onItemClick(position);
}
}
});
}
public static interface OnPlayClickListener {
// true add; false cancel
public void onItemClick(int position);
}
// add click callback
OnPlayClickListener onItemPlayClick;
public void setOnPlayClickListener(OnPlayClickListener onItemPlayClick) {
this.onItemPlayClick = onItemPlayClick;
}
Activity 中
adapter.setOnPlayClickListener(onItemActionClick);
OnPlayClickListener onItemActionClick = new OnPlayClickListener() {
@Override
public void onItemClick(int position) {
System.out.println("点击。。。"+position);
//业务处理
}
};