我有一个RecyclerView适配器,需要在每个项目内的几个视图上实现OnClick侦听器。但是,OnClick侦听器需要更改侦听器之外的变量,但这是一个问题,因为它只能在OnClick侦听器中使用最终变量。这是我实现OnClick监听器的代码:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final boolean liked = false;
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// here I can only reference a final variable, but I need to change it
if (!liked){
liked = true;
}
}
});
}
我还尝试在ViewHolder类中将变量创建为类变量,并将其用作holder.liked,但仍需要最终。我怎么能得到这个问题呢?
答案 0 :(得分:2)
尝试在扩展视图上实现onClickListener:
private class LikeHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private boolean mLiked = false;
public LikeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.your_holder_layout, parent, false));
itemView.setOnClickListener(this);
...
}
@Override
public void onClick(View view) {
if (!mLiked){
mLiked = true;
}
}