Search code examples
javaandroidlibgdxlistener

Libgdx Issues managing a single Clicklistener


In Libgdx, I'm attempting to set a Clicklistener to a specific circumstance when a specific button is pressed.

public void setExamine(final ClickListener cl) {
        examine.addListener(cl);
}

This is code I have from within a class which can be accessed from another class by doing:

table.setExamine(new ClickListener(){...});

however, doing so means that it will add a new ClickListener every time.

Instead of having this occur, is there any way to have it manage a single click listener instead of adding one? I've tried using

public void setExamine(final ClickListener cl) {
            examine.clearListeners();
            examine.addListener(cl);
}

but it seems to completely remove any functionality of the button clicking.


Solution

  • You can hold the reference of "cl" which you are passing to setExamine method in your class. Then you can remove this specific listener first in your setExamine method. I assume that examine is a scene2d actor.

    private ClickListener clickListener;
    
    public void setExamine(final ClickListener cl) {
       if(clickListener != null) {
          examine.removeListener(clickListener);
       }
       examine.addListener(cl);
       clickListener = cl;
    }
    

    If you want to apply a solution like clearListeners(), you should keep default listener of the button.

    while(examine.getListeners().size > 1) {
       examine.removeListener(examine.getListeners()[1]);
    }