就像标题中所说的,我想更改按钮的背景(使用 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/