我想将以下两个按钮(button1& button2)组合成一个clicked()方法 这与使用v.getId()的Android类似。
在LibGDX中:
button1.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y){
button1.setText("It was the first button.");
}
});
button2.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y){
button2.setText("It was the second button.");
}
});
在Android中:
View.OnClickListener action = new View.OnClickListener() {
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
// It was the first button.
break;
case R.id.button2:
// It was the second button.
break;
}
}
}
感谢您的回复。
答案 0 :(得分:2)
您可以获取actor(在本例中为按钮),然后执行if-else语句以获得类似的行为。可以将此单击侦听器分配给每个按钮。如果你这样做而没有将按钮存储在成员变量中,那么你需要先声明按钮并使它们成为最终的。
ClickListener clickListener = new ClickListener (){
public void clicked(InputEvent event, float x, float y){
Actor actor = event.getListenerActor();
if (actor == button1) doButton1Action();
else if (actor == button2) doButton2Action();
else if (actor == button3) doButton3Action();
}
}
您也可以使用更改侦听器执行此操作,并且稍微简单一些。
ChangeListener changeListener = new ChangeListener (){
public void changed (ChangeEvent event, Actor actor) {
if (actor == button1) doButton1Action();
else if (actor == button2) doButton2Action();
else if (actor == button3) doButton3Action();
}
}
答案 1 :(得分:1)
我认为拥有两个ClickListener更容易,但您可以将侦听器添加到包含按钮(或Stage或按钮所在的任何Object)的View中,并在clicked()方法中检查哪个按钮( x,y)坐标适用于:
new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
if (x > button1.x && x < button1.x + button1.width
&& y > button1.y && y < button1.y+button1.height) {
// button 1 was pressed
}
// similar for button2
}