我正在使用android recyclerview。我在每个项目上都有一个按钮。当我第一次点击按钮时,没有任何反应,但我单击双按钮,它可以工作。 贝娄,这是我的代码:
public class NewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@BindView(R.id.image_news)
public ImageView imageNews;
@BindView(R.id.text_title_news)
public TextView textTitleNews;
@BindView(R.id.text_description_news)
public TextView textDescriptionNews;
@BindView(R.id.text_time)
public TextView textTime;
@BindView(R.id.button_share)
public Button buttonShare;
@BindView(R.id.button_save)
public Button buttonSave;
public NewsViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
buttonShare.setOnClickListener(this);
buttonSave.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == buttonSave.getId()) {
Log.e("clicked", "save");
} else if (v.getId() == buttonShare.getId()) {
Log.e("clicked", "share");
}
}
}
请帮助!!!
答案 0 :(得分:0)
尝试匿名初始化每个onclicklistener,如下所示:
buttonShare.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
}
});
buttonSave.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something else
}
});
如果您想避免这种情况,可以尝试使用switch case而不是if语句
答案 1 :(得分:0)
试试这段代码:
public class NewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@BindView(R.id.image_news)
public ImageView imageNews;
@BindView(R.id.text_title_news)
public TextView textTitleNews;
@BindView(R.id.text_description_news)
public TextView textDescriptionNews;
@BindView(R.id.text_time)
public TextView textTime;
@BindView(R.id.button_share)
public Button buttonShare;
@BindView(R.id.button_save)
public Button buttonSave;
public NewsViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
buttonShare.setOnClickListener(this);
buttonSave.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_share:
Log.e("clicked", "share");
break;
case R.id.button_save:
Log.e("clicked", "saved");
break;
}
}
答案 2 :(得分:0)
由于您使用的是ButterKnife,我建议您使用ButterKnife注释在按钮上执行点击操作
@OnClick({R.id.button_share, R.id.button_save})
public void onClick(View view) {
switch (view.getId()) {
case R.id.button_share:
// Do something
break;
case R.id.button_save:
// Do something
break;
}
}
并使用开关代替if,以提高可读性。