Programmatically perform click on Actor libgdx

痞子三分冷 提交于 2019-12-22 05:58:08

问题


My question is straightforward.

I have some ClickListeners added to an Actor. I want to execute a click event on them programmatically.

Something like myActor.performClick();


回答1:


You can also use:

InputEvent event1 = new InputEvent();
event1.setType(InputEvent.Type.touchDown);
button.fire(event1);

InputEvent event2 = new InputEvent();
event2.setType(InputEvent.Type.touchUp);
button.fire(event2);

This will also show any pressed image change which can be helpful.




回答2:


I figured out a solution :

public static void performClick(Actor actor) {
    Array<EventListener> listeners = actor.getListeners();
    for(int i=0;i<listeners.size;i++)
    {
        if(listeners.get(i) instanceof ClickListener){
            ((ClickListener)listeners.get(i)).clicked(null, 0, 0);
        }
    }
}

This method can be called passing the actor on whom click needs to be performed




回答3:


I do it like this (seems nicer to me):

public void triggerButtonClicked(Button button) {
    InputEvent inputEvent = Pools.obtain(InputEvent.class);
    inputEvent.reset();
    inputEvent.setButton(0);
    inputEvent.setRelatedActor(button);

    try {
        inputEvent.setType(InputEvent.Type.touchDown);
        button.fire(inputEvent);

        inputEvent.setType(InputEvent.Type.touchUp);
        button.fire(inputEvent);
    } finally {
        Pools.free(inputEvent);
    }
}


来源:https://stackoverflow.com/questions/25870645/programmatically-perform-click-on-actor-libgdx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!