-
Notifications
You must be signed in to change notification settings - Fork 378
Recovering data from the Cards
Both onDismiss
and the click methods (onItemClick
and onItemLongClick
) provide the Card/CardItemView the user interacted with, so I thought that it would be useful if you could store data inside your cards, and then recover it when the user interacts with the Card.
In order to do that, Card (the base class, so every derivated class offers it too) offers a setTag(Object)
and getTag()
methods, which you can use to store data in it.
As it receives an Object, you can use a personal class to store your data.
In example, let's say that you want to save a Person and an id inside your Card.
public class MyData {
private Person person;
private int id;
public MyData(Person person, int id){
this.person = person;
this.id = id;
}
public Person getPerson(){
return person;
}
public int getId(){
return id;
}
}
Once you have defined your data storage class, you can simply set it and recover it:
// Create your data
Person p = new Person("John", 42);
int id = 10;
// Store it inside a MyData object
MyData data = new MyData(p, id);
// Create your card
SmallImageCard card = new SmallImageCard(context);
// Do whatever you want with it
// Set the MyData object to it
card.setTag(data)
listView.add(card);
mListView.addOnItemTouchListener(new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(CardItemView view, int position) {
MyData data = (MyData)view.getTag();
String name = data.getPerson().getName();
Log.d("NAME", name);
}
@Override
public void onItemLongClick(CardItemView view, int position) {
MyData data = (MyData)view.getTag();
int id = data.getId();
Log.d("ID", id+"");
}
});
As you can see, it's a very flexible option that allows every developer to store his data inside a Card, no matter which type it is.