Get a list that I sent to the Adapter within the Viewholder

0

They commented to me that it is the ideal practice to use the OnClick inside the ViewHolder, but if with the OnClick I should use the values within the list that I use in the Adapter, how can I get the list? I just passed the list to static, but I feel it's wrong to do so.

Is it wrong to do so? What other way is there?

    
asked by Eduardo Ricardez 27.04.2017 в 17:49
source

1 answer

2

Good practices indicate that it is better to do the assignment of ViewHolder and with the function getAdapterPosition() you can get the position by clicking on the element, so you can get the data with tu_lista[posición] or tu_lista.getItem(posición)

class ViewHolder extends RecyclerView.ViewHolder {

    Context mContext;
    ImageView ivPhoto;
    TextView tvTitle;

    ViewHolder(View itemView) {
        super(itemView);
        mContext = view.getContext(); //obtener el context si se necesita más adelatne
        ivPhoto = (ImageView) itemView.findViewById(R.id.iv_photo);
        tvTitle = (TextView) itemView.findViewById(R.id.tv_title);

        ivPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "viewClick on " + mTitle.getText() + " position " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
                //Aquí puedes recuperar datos tu_lista[getAdapterPosition()]
            }
        });
    }
}

Compute the click

The parent container is itemView

In any element The click listener must be assigned to the parent container itemView if the parent container is a layout as LinearLayout , RelativeLayout etc .. the attribute android:clickable="true" must be assigned so that it can receive the click.

For a simple click:

itemView.setOnClickListener(new View.OnClickListener()...

For a long press:

itemView.setOnLongClickListener(new View.OnLongClickListener()...

Each item separately If in the view we want that if you click on the image you should compute something like the icon favorito

ivPhoto.setOnClickListener(new View.OnClickListener()...

    
answered by 27.04.2017 / 18:51
source