I am using this library in my app: Card Library : Guide and created a card as shown in the example.
Now I need to handle a click event, but I receive an error when instantiating the following: new Card.OnCardClickListener
, which says OnCardClickListener is abstract: cannot be instantiated
.
In my Activity I have this code:
Card card = new Card(getBaseContext());//getContext()
CardHeader header = new CardHeader(getBaseContext());
card.addCardHeader(header);
final CardViewNative cardView = (CardViewNative) findViewById(R.id.carddemo);
cardView.setCard(card);
cardView.setClickable(true);
cardView.setOnClickListener(new Card.OnCardClickListener()); //error here
What's wrong? How can I set my card as clickable and then handle click/touch events?
EDIT
If I use it this way:
cardView.setOnClickListener(new Card.OnCardClickListener(){//error here
@Override
public void onClick(Card card, View view) {
// This will execute when the the card is clicked
}
});
it says cannot resolve method setOnClickListener(it.gmariotti.cardslib.library.internal.Card.OnCardClickListener)
EDIT1
You guys are right, I set the setOnClickListener
on the card itself, and there's no error anymore,
but still it doesn't perform any action when the card is clicked. That's the new code:
//Create a Card
Card card = new Card(this);//getContext()
//Create a CardHeader
CardHeader header = new CardHeader(this);
//....
//Add Header to card
card.addCardHeader(header);
//Set card in the cardView
CardViewNative cardView = (CardViewNative) this.findViewById(R.id.carddemo);
cardView.setCard(card);
card.setClickable(true);
card.setOnClickListener(new Card.OnCardClickListener(){
@Override
public void onClick(Card card, View view) {
// This will execute when the the card is clicked
Toast.makeText(CardMariotti.this,"Clickable card", Toast.LENGTH_LONG).show();
}
});
I performed a debug, but the onClick
method is never called. How come?
Card.OnCardClickListener is an Interface. You must create the class that defines how the functions within the interface are to be used. Try this:
card.setOnClickListener(new Card.OnCardClickListener() {
@Override
public void onClick(Card card, View view) {
// This will execute when the the card is clicked
}
});
Source for answer: https://github.com/gabrielemariotti/cardslib/blob/master/doc/CARD.md#clickable-card
Information on Java interfaces: Java Interfaces?
EDIT
Furthermore, remove android:clickable="true"
from the RelativeLayout contained by the card. It's stealing the click for itself.