Search code examples
androidandroid-recyclerviewontouchlistenerswiperefreshlayout

RecyclerView ItemTouch Listener gets called everytime


I have implemented a RecyclerView in a layout that has SwipeRefreshLayout. I find the RecyclerView, set its adapter as well as call the addOnItemTouchListener() inside a method. This method is called everytime the SwipeRefreshLayout has been refreshed.
Inside the Touch Listener, an AlertDialog is called and displayed.
Everytime I refresh in the SwipeRefreshLayout it seems to be adding a Touch Listener. What ends up happening is the AlertDialog is now displayed more than once depending on how many times you have refreshed.
How can I go about fixing this such that even when it is refreshed the Dialog is only shown once?:

private void initRecyclerView() {
    RecyclerView ticketRecyclerView = (RecyclerView) findViewById(R.id.recycler_tickets);
    ticketsAdapter = new TicketsAdapter(this);
    ticketRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    ticketRecyclerView.setAdapter(ticketsAdapter);
    ticketRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, ticketRecyclerView, new ClickListener() {
}
}

Solution

  • Each time you refresh, you are adding an OnItemTouchListener. This does not replace the previously added listeners; it just adds to them.

    To correct this, you will have to either not add additional touch listeners on a refresh or remove the last one.

    removeOnItemTouchListener

    void removeOnItemTouchListener (RecyclerView.OnItemTouchListener listener)

    Remove an RecyclerView.OnItemTouchListener. It will no longer be able to intercept touch events.