web-dev-qa-db-fra.com

RecyclerView OnClick ne fonctionne pas

J'ai créé une vue de recyclage horizontale à l'intérieur d'un fragment. Désormais, lorsque je clique sur un élément, je ne vois pas le programme d'écoute sur le clic activé. Voici mon code pour la classe Adapter:

public class FeaturedProductsAdapter  extends RecyclerView.Adapter<FeaturedProductsAdapter.CustomViewHolder> {
private List<FeaturedProductInfo> feedItemList;
private Context mContext;

public FeaturedProductsAdapter(Context context, List<FeaturedProductInfo> feedItemList) {
    this.feedItemList = feedItemList;
    this.mContext = context;
}
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    protected ImageView imageView;
    protected TextView textView,priceView;
    private Context context;


    public CustomViewHolder(View view,Context context) {

        super(view);
        this.context=context;
        this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
        this.textView = (TextView) view.findViewById(R.id.prodTitle);
        this.priceView = (TextView) view.findViewById(R.id.prodPrice);
        view.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        int position = getLayoutPosition(); // gets item position
        Log.e("Check", position + "");
        FeaturedProductInfo user = feedItemList.get(position);//[position];
        // We can access the data within the views
        Intent intent = new Intent(context, ProductDescription.class);
        intent.putExtra("id", user.getId());
        mContext.startActivity(intent);


    }

}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.featured_product_list_item_card, null);
    Context context = viewGroup.getContext();

    CustomViewHolder viewHolder = new CustomViewHolder(view,context);

    return viewHolder;
}

@Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
    FeaturedProductInfo feedItem = feedItemList.get(i);

    //Download image using picasso library
    if(!feedItem.getUrl().contains("."))
    {
        feedItem.setUrl("nothing");
    }
    Picasso.with(mContext).load(feedItem.getUrl())
            .error(R.drawable.unavailable)
            .placeholder(R.drawable.unavailable)
            .resize(110,110)
            .into(customViewHolder.imageView);

    //Setting text view title
    customViewHolder.textView.setText(feedItem.getTitle());
    customViewHolder.priceView.setText(feedItem.getPrice());
    //Log.e("Featured: ","SET");
}

@Override
public int getItemCount() {
    return (null != feedItemList ? feedItemList.size() : 0);
}

}

Je pense que je ne comprends pas comment utiliser correctement le détenteur de vue. Alors que j'ai utilisé le même code pour recyclerVoir dans une autre activité et cela fonctionne comme un charme. 

7
Akshay Bhasin

1.Simple Click Handler dans ViewHolder

RecyclerView ne comporte pas de dispositions spéciales permettant d'associer des gestionnaires de clics à des éléments contrairement à ListView qui utilise la méthode setOnItemClickListener(). Pour obtenir un effet similaire, nous pouvons attacher des événements de clic dans la variable ViewHolder de notre adaptateur:

public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ViewHolder> {
    // ...

    // Used to cache the views within the item layout for fast access
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView tvName;
        public TextView tvHometown;
        private Context context;

        public ViewHolder(Context context, View itemView) {
            super(itemView);
            this.tvName = (TextView) itemView.findViewById(R.id.tvName);
            this.tvHometown = (TextView) itemView.findViewById(R.id.tvHometown);
            // Store the context
            this.context = context;
            // Attach a click listener to the entire row view
            itemView.setOnClickListener(this);
        }

        // Handles the row being being clicked
        @Override
        public void onClick(View view) {
            int position = getLayoutPosition(); // gets item position
            User user = users.get(position);
            // We can access the data within the views
            Toast.makeText(context, tvName.getText(), Toast.LENGTH_SHORT).show();
        }
    }

    // ...
}

Une autre façon est ma manière préférée .. mais c'est aussi une bonne façon de s'y prendre.

Mon onBindViewHolder 

@Override
    public void onBindViewHolder(CategoryViewHolder holder, int position) {
        Category category = mCategories.get(position);

        holder.tvTitle.setText(category.getTitle());
        holder.tvDescription.setText(category.getDescription());

        holder.rlContainer.setOnClickListener(mClickListener);
        holder.rlContainer.setTag(holder);
    }

Mon niveau de classe (objet Adapter de View.OnClickListner)

View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            CategoryViewHolder holder = (CategoryViewHolder) view.getTag();
            int position = holder.getAdapterPosition();

            startAppointmentBookingFor(mCategories.get(position));
        }
    };

donc, attachez l’auditeur à n’importe quelle vue de votre titulaire (j’essaie de le mettre sur un conteneur uniquement), puis extrayez-le sur la onclick et gérez les positions, etc.

12
yUdoDis

Apportez les modifications suivantes à votre adaptateur:

public class FeaturedProductsAdapter  extends RecyclerView.Adapter<FeaturedProductsAdapter.CustomViewHolder> {
private List<FeaturedProductInfo> feedItemList;
private Context mContext;
private OnItemClickListener onItemClickListener;

public FeaturedProductsAdapter(Context context, List<FeaturedProductInfo,OnItemClickListener onItemClickListener> feedItemList) {
    this.feedItemList = feedItemList;
    this.mContext = context;
    this.onItemClickListener = onItemClickListener;

}
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    protected ImageView imageView;
    protected TextView textView,priceView;
    private Context context;


    public CustomViewHolder(View view,Context context) {

        super(view);
        this.context=context;
        this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
        this.textView = (TextView) view.findViewById(R.id.prodTitle);
        this.priceView = (TextView) view.findViewById(R.id.prodPrice);
        view.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        onItemClickListener.onItemClick(getLayoutPosition());
        Log.e("Check", position + "");
        FeaturedProductInfo user = feedItemList.get(position);//[position];
        // We can access the data within the views
        Intent intent = new Intent(context, ProductDescription.class);
        intent.putExtra("id", user.getId());
        mContext.startActivity(intent);


    }

}

public interface OnItemClickListener{
    void onItemClick(int position);
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.featured_product_list_item_card, null);
    Context context = viewGroup.getContext();

    CustomViewHolder viewHolder = new CustomViewHolder(view,context);

    return viewHolder;
}

@Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
    FeaturedProductInfo feedItem = feedItemList.get(i);

    //Download image using picasso library
    if(!feedItem.getUrl().contains("."))
    {
        feedItem.setUrl("nothing");
    }
    Picasso.with(mContext).load(feedItem.getUrl())
            .error(R.drawable.unavailable)
            .placeholder(R.drawable.unavailable)
            .resize(110,110)
            .into(customViewHolder.imageView);

    //Setting text view title
    customViewHolder.textView.setText(feedItem.getTitle());
    customViewHolder.priceView.setText(feedItem.getPrice());
    //Log.e("Featured: ","SET");
}

@Override
public int getItemCount() {
    return (null != feedItemList ? feedItemList.size() : 0);
}
0
Veeresh Charantimath