[英]LibGDX variable accessed from within inner class
我想制作一個方法(addButton),該方法將由構造函數完成所有工作,但要使用一些變量。 現在我被卡住了,因為有一個錯誤提示我需要進行布爾最終運算,但是我不想這樣做。 我應該怎么做?
這是代碼:
public void addButton(Table table,String key,boolean bool){
atlas=new TextureAtlas(Gdx.files.internal("buttons/buttons.pack"));
skin=new Skin(atlas);
buttonStyle.up=skin.getDrawable(key+".up");
buttonStyle.down=skin.getDrawable(key+".down");
button=new Button(buttonStyle);
button.addListener(new ClickListener(){
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
bool=true; //this boolean
return super.touchDown(event, x, y, pointer, button);
}
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
bool=false; //and this
super.touchUp(event, x, y, pointer, button);
}
});
table1.add(button);
}
有很多方法可以做到這一點。 如果您只想知道按鈕是否被按下,則可以使用Button.isPressed()
,因為Button
已經在跟蹤它了。
如果您想做其他事情,最好創建自己的MyButton
來extends Button
。 MyButton
可以具有一個字段private boolean bool
ClickListener
private boolean bool
,並將該ClickListener
添加到構造函數中。 然后,該單擊偵聽器將能夠通過MyButton.this.bool
訪問按鈕的字段並進行更改。
public class MyButton extends Button {
private boolean bool;
public MyButton(...) {
addListener(new ClickListener(){
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
MyButton.this.bool=true;
return super.touchDown(event, x, y, pointer, button);
}
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
MyButton.this.bool=false;
super.touchUp(event, x, y, pointer, button);
}
});
}
}
另一個解決方案是保留當前設置,但將原始值包裝在另一個類中:
public class DataWrapper {
public boolean bool;
}
public void addButton(Table table,String key, final DataWrapper data) {
...
button=new Button(buttonStyle);
button.addListener(new ClickListener(){
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
data.bool=true;
return super.touchDown(event, x, y, pointer, button);
}
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
data.bool=false;
super.touchUp(event, x, y, pointer, button);
}
});
table1.add(button);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.