android - 按钮上的背景和文本

标签 android android-widget

就像标题中所说的,我想更改按钮的背景(使用 setBackgroundResource() ),但是当我这样做时,我看不到我放在上面的文本(使用 setText() ),我找到了类似的主题,但仅限于 xml anwser。我需要在代码中执行此操作...

谢谢'

类代码:

public class CityButton extends Button {
    private double ratioX;
    private double ratioY;
    private City city;

public CityButton(Context context, City city, double ratioX, double ratioY) {
    super(context);

    this.city = city;

    Rect boundRect = this.getBackground().getBounds();
    this.setHeight(boundRect.height());
    this.setWidth(boundRect.height());

    this.ratioX = ratioX;
    this.ratioY = ratioY;
}

public void addReinforcements(int value) {
    city.addReinforcements(value);
    reinforcementView.setText("" + city.getReinforcements());
}

public void setOffset(int posX, int posY) {
    int offsetX = (int) (posX * this.ratioX) - 5;
    int offsetY = (int) (posY * this.ratioY) - 5;

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(this.getLayoutParams());
    params.setMargins(offsetX, offsetY, offsetX + this.getWidth(), offsetY + this.getHeight());
    this.setLayoutParams(params);
}

最佳答案

我认为 setBackgroundResource 可能会产生丢失偏移设置的副作用。每次更改背景后尝试调用 setOffset:

public void setBackgroundResource(int resid, int posX, int posY) {
    super.setBackgroundResource(resid);
    setOffset(posX, posY);
}

关于android - 按钮上的背景和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7900653/

相关文章:

android - 如何在 main.xml 中实现方形布局和按钮?

android - 分析 v4 未捕获的异常不起作用

Android ADT 调试挂起尝试连接到端口 8601 上的调试器?

Android:style.xml 中的重力属性不起作用

java - 关闭应用程序后小部件停止工作

android - 如何在小部件配置 Activity 中获取小部件名称(提供者)?

java - Append 方法在 StringBuilder 中不起作用

android - 有没有像ICS的解锁屏一样 "Drag and Drop to unlock"组件的开源项目?

java - 从处理程序调用时,asynctask 未获取 arraylist

android - Kotlin + MVP - 意外覆盖