Set onItemClickListener inside onBindViewHolder() with RecyclerView.Adapter

后端 未结 5 1066
自闭症患者
自闭症患者 2021-02-14 03:54

I have a custom object :

Student.class

public class Student {
  private String name;
  private String age;

  public String getName() {
    return name;
         


        
5条回答
  •  执念已碎
    2021-02-14 04:14

    Simplest way is holding single ItemClickListener inside your Adapter:

    public class WalletListRecyclerAdapter extends RecyclerView.Adapter {
        private List wallets;
        private ItemClickListener itemClickListener;
    
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Wallet wallet = wallets.get(position);
    
            holder.root.setOnClickListener(v -> {
                if (itemClickListener != null)
                    itemClickListener.onClick(holder.root, wallet);
            });
        }
    
        static class ViewHolder extends RecyclerView.ViewHolder {
            View root;
    
            public ViewHolder(View v) {
                super(v);
                root = v;
            }
        }
    
    
        public void setItemClickListener(ItemClickListener itemClickListener) {
            this.itemClickListener = itemClickListener;
        }
    
        public interface ItemClickListener {
            void onClick(View view, Wallet wallet);
        }
    }
    

    In Activity:

    walletsAdapter = new WalletListRecyclerAdapter();
    walletsAdapter.setItemClickListener((view, wallet) -> {
        Intent intent = new Intent(this, WalletActivity.class);
        intent.putExtra(Const.KEY_WALLET, wallet);
        startActivity(intent);
    });
    

提交回复
热议问题