简体   繁体   中英

RecyclerView Adapter OnClick parameter

I have a RecyclerView Adapter which needs to implement OnClick listeners on several of the views inside each item. However, the OnClick listener needs to change a variable outside of the listener, but this is a problem since it can only use final variables inside the OnClick listener. Here is my code where I implements the OnClick listener:

@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;
            }
        }
    });
}

I also tried to create the variable as a class variable in the ViewHolder class and use it as holder.liked, but still it needs to be final. How can i get aroud this issue?

Try implementing onClickListener on an extended viewholder instead:

 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM