背景和文本在按钮上

时间:2011-10-26 09:04:26

标签: 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);
}

1 个答案:

答案 0 :(得分:0)

我认为setBackgroundResource可能会导致丢失偏移设置的副作用。更改背景后,每次尝试拨打setOffset

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