仅以此篇记录最最基本的接口回调的处理,常见的使用是:recyclerview的条目点击事件...
以recylerview的条目点击事件为例,步骤:
1.在Adapter中定义MyOnItemClickListener接口, 在接口中定义抽象方法
public interface MyOnItemClickListener{
void onItemClick(int position);
}
- 声明成员变量private MyOnItemClickListener mMyOnItemClickListener;
- 提供set方法,将别人传入的监听器保存为成员变量 this.mOnBtnClickListener = onBtnClickListener;
public void setMyOnItemClickListener(MyOnItemClickListener myOnItemClickListener){
this.mMyOnItemClickListener = myOnItemClickListener;
}
- 在onBindViewHolder中调用Listener.onItemClick()方法
public void onBindViewHolder(MyViewHolder holder, final int position) {
int resId = resIdList.get(position);
holder.mImageView.setImageResource(resId);
holder.itemView.setOnClickListener(new View.OnClickListener() { 给整个条目绑定点击事件
@Override
public void onClick(View v) {
if (mMyOnItemClickListener!=null){
mMyOnItemClickListener.onItemClick(position);
}
}
});
}
- 在adapter外部即可调用这个接口回调即可
recyclerAdapter1.setMyOnItemClickListener(new RecyclerAdapter.MyOnItemClickListener(){
public void onItemClick(int position){
Toast.makeText(RecyclerViewActivity.this, "点击了:"+position, Toast.LENGTH_SHORT).show();
}
});
网友评论