RecyclerViewのitemクリックイベントを実現する内部リスナー

6968 ワード

コードは次のとおりです.
public class myViewholder extends RecyclerView.ViewHolder implements View.OnClickListener{
    private TextView tv_bookname;
    private TextView tv_bookauthor;
    private TextView tv_bookintroduce;
    private ImageView img_book;

    public myViewholder(View itemView) {
        super(itemView);
        tv_bookname= (TextView) itemView.findViewById(R.id.item_bookname);
        tv_bookauthor= (TextView) itemView.findViewById(R.id.item_bookauthor);
        tv_bookintroduce= (TextView) itemView.findViewById(R.id.item_bookintroduce);
        img_book= (ImageView) itemView.findViewById(R.id.item_bookimage);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Log.d(TAG,"onClick--position:"+getAdapterPosition());
        //     
        //    ,     
        Intent intent=new Intent(context,DetailsActivity.class);
       intent.putExtra("book_callnum",(String)list.get(getAdapterPosition()).get("book_callnumber"));
       context.startActivity(intent);

    }
}

まずmyView holderがViewのクリックイベントのインタフェースを実現し、その後リスナー(黄色のハイライトコード行)が設置され、その後肝心な点はクリックがどれなのかを確定することであり、偶然にもView holderというクラスにgetAdapterPosition()という方法があるので、どの項目がクリックされたのかを確定するのに重要な役割を果たし、クリックによって異なることをするのは簡単です.