按钮上的背景和文本
就像标题中所说,我想更改按钮的背景(使用 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);
}
like said in the title I'd like to change a button's backgroun (using setBackgroundResource() ), but when I do that, I can't see the text I'm puting on it (with setText() ), I found similar subject, but only with xml anwser. I need to do this in code...
Thank'
Class Code:
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为
setBackgroundResource
可能会产生丢失偏移设置的副作用。每次更改背景后尝试调用setOffset
:I think
setBackgroundResource
may have the side effect of losing your offset settings. Try to callsetOffset
each time after you change background: