在Andoird中喜滨,當activity中需要處理adapter中ListView/或者其他列表的item點擊事件,這時候需要用到回調(diào)接口撤防。
方式:在Adapter中定義的接口(相當于發(fā)布)虽风,在activity中實現(xiàn)Adapter中定義的接口(相當于是響應)。
這樣activity中便能輕松獲取adapter中的數(shù)據(jù):
①回調(diào)接口可以把adapter中處理過的數(shù)據(jù)傳給activity寄月。
②Activity中獲取item中數(shù)據(jù)可以直接用 adapter.getItem(position)獲取辜膝,也可以直接在activity獲取到的數(shù)據(jù)中獲取
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);
//業(yè)務處理
}
};