javalibgdxclicklistener

libGDX: Delay in ClickListener


I want to change a button style when I'm clicking on this button. This is my solution:

show(){
   ...
   Gdx.input.setInputProcessor(stage);
   stage.add(myButton); 
}

public void render(float delta){
   final boolean buttonSwitch;
   myButton.addListener(new ClickListener() {
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {

            if(buttonSwitch == true)
            {
                  myButton.setStyle(style1);
            }
            else 
            {
                  myButton.setStyle(style2);
            }
        }
    });
}

The problem is that sometimes my clicks will be ignored and the style will not be changed. I have to click three times or more to get a result.


Solution

  • Adding Listener in render method ?? why !!

    Remove below code snippet from render method and keep in show() method

    final boolean buttonSwitch;
    myButton.addListener(new ClickListener() {
            public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
    
                 myButton.setStyle(buttonSwitch?style1:style2);
                 buttonSwitch=!buttonSwitch;   
            }
        });