Search code examples
androidandroid-recyclerviewonclicklistenerandroid-button

OnClickListener on not always visible button inside RecyclerView


When the red button is pressed, the orange button appears.
When the red button is pressed again, the orange button disappears.
(Basically a toggle)

enter image description here

This happens with notifyDataSetChanged() and different ItemViewTypes.

Two questions:

  1. Do I need to register OnClickListener every time, and de-register it too?
    Or does it de-register automatically when it is removed from RecyclerView through notifyDataSetChanged() and I just have to add it every time?
  2. Should I put associated methods with register etc. in the Activity/Fragment or in the RecyclerViewAdapter?

onCreateViewHolder code:

@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder;
        View view;

        if (viewType == ADD_FOOTER_ITEM) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_sa_add_footer_item, parent, false);
            holder = new AddFooterViewHolder(view);
        } else if (viewType == INPUT_ITEM) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_sa_input_item, parent, false);
            holder = new InputViewHolder(view);
        } else {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_sa_item, parent, false);
            holder = new CustomViewHolder(view, this);
        }

        return holder;
}

recycler_view_sa_add_footer_item.xml is basically just a FrameLayout with an ImageButton and some visual stuff in it. The question is about that one ImageButton.


Solution

    1. No. If you do not unregister you have not to register it back. OnClickListener will be always there attached to ViewHolder in ViewPool.
    2. The best way is to define your Listener inside RecyclerViewAdapter and register it in onCreateViewHolder method.