Lajos Neto Lajos Neto - 4 months ago 39
Android Question

Get card data and pass to intent when clicked

I'm working with

CardView
and got stuck in a little problem. I have a
RecyclerView
where i am displaying some cards.

The problem is how to pass a card variable to another
activity
when it is clicked?

I Have the following View Holder:

public class DisciplinaViewHolder extends RecyclerView.ViewHolder {

protected TextView disciplinaNome;
protected TextView disciplinaCodigo;
protected TextView disciplinaCriador;
protected TextView disciplinaProfessor;
protected TextView disciplinaPeriodo;
protected CardView card;
protected ImageButton calendarButton;

public DisciplinaViewHolder(View itemView) {
super(itemView);

disciplinaNome = (TextView) itemView.findViewById(R.id.nome);
disciplinaCodigo = (TextView) itemView.findViewById(R.id.codigo);
disciplinaCriador = (TextView) itemView.findViewById(R.id.criadaPor);
disciplinaProfessor = (TextView) itemView.findViewById(R.id.professor);
disciplinaPeriodo = (TextView) itemView.findViewById(R.id.periodo);


calendarButton = (ImageButton) itemView.findViewById(R.id.calendarBuutton);
calendarButton.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), CalendarActivity.class);
v.getContext().startActivity(intent);
}
});

card = (CardView) itemView;
}
}


An example would be: Supposing I have 3 cards:

>Card1(name = "First Card"),
>Card2(name = "Second Card"),
>Card3(name = "Third Card").


When I press a
button
inside one of these cards, I want to get the name variable from the pressed card and pass it inside a
intent
on the
onClick()
method. So, if I press the
button
inside Card1, I would pass the value "First Card" to my next
activity
.

Thank you in advance.

Answer

Use extras for that :

Intent intent = new Intent(v.getContext(), CalendarActivity.class);
intent.putExtra("extraName", extraValue);

please notice you will get issues launching the good activity with your method. Since RecyclerViews recycle list items, you need to set the click listener in the onBindViewHolder method and not in the ViewHolder constructor.