很抱歉这个通用标题,但我找不到更好的配方。 我在我的android项目中包含了库Swipeable-Cards。 在MyActvitiy.java中,oncreate方法包含类似的内容:
mCardContainer = (CardContainer) findViewById(R.id.layoutview);
SimpleCardStackAdapter adapter = new SimpleCardStackAdapter(this);
adapter.add(new CardModel("Title2", "Description2 goes here", r.getDrawable(R.drawable.picture2)));
adapter.add(new CardModel("Title3", "Description3 goes here", r.getDrawable(R.drawable.picture3)));
CardModel cardModel = new CardModel("Title1", "Description goes here", r.getDrawable(R.drawable.picture1));
cardModel.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() {
@Override
public void onLike() {
Log.i("Swipeable Cards","I like the card ");
}
});
adapter.add(cardModel);
mCardContainer.setAdapter(adapter);
我希望能够在onLike()上记录对象的标题。但是,我不知道如何访问它。
伪码:
cardModel.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() {
@Override
public void onLike() {
Log.i("Swipeable Cards","I like the card with the title: " + this.getTitle());
// should show Title1, Title2, Title3 after 3 swipes.
}
});
CardModel类已经包含方法getTitle(),我只是不知道如何访问它!
public String getTitle() {
return title;
}
答案 0 :(得分:1)
你必须对这个OnCardDimissedListener
进行分类并将参数传递给它,就像这样:
public class MyOnCardDimissedListener implements OnCardDimissedListener{
private String title;
public MyOnCardDimissedListener(String title){
this.title = title;
}
@Override
public void onLike() {
Log.i("Swipeable Cards", title);
}
}
然后你就这样使用它:
cardModel.setOnCardDimissedListener(new MyOnCardDimissedListener(cardModel.getTitle()));
你去... MyOnCardDimissedListener
的每个实例都有一个标题的引用。我认为这有点浪费,但另一种方法是编辑库源代码以在其监听器上传递CardModel
对象。
答案 1 :(得分:0)
这是面向对象编程中最基本的规则之一 创建一个CardModel对象并调用该对象的方法。
CardModel cardModel = new CardModel(...);
cardModel.getTitle();
那就是它!