首先recyclerview的item单击事件是通过接口回调的方式来实现的,接口回调实质就是一个类A将获取到的数据传递给接口,然后类A的示例通过接口来获取数据。
第一步:在你的设配器中声明对外的接口,如下:
public void setJieKou(RecyclerInterface recyclerInterface) {
this.recyclerInterface = recyclerInterface;
}
第二步:在onCreateViewHolder方法中给根布局绑定单击事件,如下:
public MyHolderView onCreateViewHolder(ViewGroup parent, int viewType) {
View view=LayoutInflater.from(context).inflate(R.layout.recycler_item,null);
view.setOnClickListener(this);
myHolderView=new MyHolderView(view);
return myHolderView;
}
第三步:在onBindViewHolder方法中给根布局添加position数据,如下:
public void onBindViewHolder(MyHolderView holder, int position) {
if(position==5){
holder.more.setVisibility(View.VISIBLE);
holder.linearLayout.setVisibility(View.GONE);
holder.itemView.setTag(position);
}else {
holder.textView.setText(listDatas.get(position).getArticle_name());
RequestOptions requestOptions=RequestOptions.centerCropTransform().optionalTransform(new MyTransition(context));
Glide.with(context).applyDefaultRequestOptions(requestOptions).load(listDatas.get(position).getContentPictures().get(0)).into(holder.imageView);
holder.itemView.setTag(position);
}
}
第四步:然后在根布局的单击事件中将根布局和position传递给接口,如下:
public void onClick(View v) {
recyclerInterface.danJi(v, (Integer) v.getTag());
}
第五步:在调用设配器的地方,设置回调即可,如下:
myAdapter.setJieKou(new RecyclerInterface() {
@Override
public void danJi(View view, int position) {
if (position == 5) {
Intent intent = new Intent(getActivity(), GaoXiaoActivity.class);
startActivity(intent);
} else
click_xiaohua(position);
}
});
注:
public interface RecyclerInterface {
void danJi(View view, int position);
}
网友评论