改变Libgdx按钮外观

4

我需要能够在触发我的一些事件时更改Libgdx Button的外观。

以下是我的按钮声明:

Button googleButton = new Button(skin.getDrawable("google_sign_in"));

下面是我尝试过的方法:

googleButton.setBackground(skin.getDrawable("google_sign_out"));
googleButton.invalidate();

googleButton.setChecked(true);
googleButton.invalidate();

googleButton.getStyle().up = skin.getDrawable("google_sign_out");
googleButton.invalidate();

我已经做了很多搜索,但是找不到答案。有人能向我展示正确的方法吗?


问题是我不希望它在上下事件中改变外观,而是与按钮本身没有关联的事件需要切换其图像。 - Raphael Royer-Rivard
我需要能够更换图片,而不是保持相同的图片。也许我不需要使用按钮,那么我应该使用哪种演员才能在运行时更改其图像? - Raphael Royer-Rivard
你能也发布“google_sign_in”的样式吗? - Xavier Guzman
这并不是一种样式,而是一种可绘制对象。 - Raphael Royer-Rivard
5个回答

6
我认为问题在于您在初始化Button后更改了皮肤/样式的内容,但是按钮对象在初始化后不再引用样式。 我也不完全清楚您的目标是什么。 我假设您想显示一个“登录”按钮,直到用户登录,然后您希望该按钮成为“注销”按钮。 invalidate方法只触发重新布局(重新计算Actor的大小/位置)。
也许尝试使用setStyle强制使用样式,像这样:
   googleButton.getStyle().up = ... whatever;
   googleButton.setStyle(googleButton.getStyle());

话虽如此,我认为你最好拥有两个不同的Button对象(一个用于登录,一个用于退出)。将它们打包在Stack中,只需使其中之一不可见即可(参见{{link2:Actor.setVisible}})


我已经尝试在初始化后设置样式,但它没有任何作用。诚挚地说,堆栈完全无用,它只是一个向量,它不会改变其中元素的z索引...我成功地通过像你建议的那样切换两个按钮的可见性来改变按钮的可见性。我只是希望有一种方法可以只使用一个演员来完成这个操作。 - Raphael Royer-Rivard

2

我成功让它工作了。在我的演员中,有一个骰子,有6个可能的图像:

public Dice(int options) {
    super(new Button.ButtonStyle());
}

当我想要改变脸部时:

public void setValue(int value) {
    this.value = value;
    Button.ButtonStyle style = getStyle();
    style.up = new TextureRegionDrawable(
            Assets.instance.dices.facesUp[value]);
    style.down = new TextureRegionDrawable(
            Assets.instance.dices.facesDown[value]);
    style.checked = new TextureRegionDrawable(
            Assets.instance.dices.facesChecked[value]);
    setSize(getPrefWidth(), getPrefHeight());
}

我认为诀窍在于

setSize(getPrefWidth(), getPrefHeight());

如果我省略它,骰子就不会显示出来。而且也不需要使用setStyle或invalidate()。

1
请使用 CheckBox 类代替; 1- 为皮肤制作一个 .json 文件。
{
com.badlogic.gdx.graphics.g2d.BitmapFont: { default-font: { file: fontfile.fnt } },
com.badlogic.gdx.graphics.Color: {
    green: { a: 1, b: 0, g: 1, r: 0 },
    white: { a: 1, b: 1, g: 1, r: 1 },
    red: { a: 1, b: 0, g: 0, r: 1 },
    black: { a: 1, b: 0, g: 0, r: 0 }
  },
com.badlogic.gdx.scenes.scene2d.ui.CheckBox$CheckBoxStyle: {
    google-loggin: { checkboxOn: google_sign_in, checkboxOff: google_sign_out, font: default-font, fontColor: white }
},
}

2- 制作一个皮肤

skin = new Skin(Gdx.files.internal("your.json-file.json"), new TextureAtlas("textureAtlas-file.pack"));

3- 创建一个忽略第一个参数的按钮:

CheckBox loginButton = new CheckBox("", skin, "google-loging");

0

您必须将图像添加到按钮中button_1.addActor(image)。这个图像将覆盖按钮原始皮肤。然后,您可以关闭或打开此图像image.setVisible(false)


0

这是给那些从Google搜索相关问题的人。如果您已经初始化,想要更改按钮样式为已添加到皮肤文件中的样式:

btn.setStyle(skin.get("YOUR BTN STYLE",TextButton.TextButtonStyle.class));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接