java如何以编程方式将图像适配到ImageButton
我正在尝试使用以下图像设置ImageButton的背景:
和代码:
一旦创建:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LightImageButton lightImageButton = new LightImageButton(false, getApplicationContext());
ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setBackground(getResources().getDrawable(lightImageButton.getCurrentImage()));
imageButton.setOnClickListener(lightImageButton);
}
辅助类:
public class LightImageButton implements View.OnClickListener {
private static final int bulbOnImg = R.drawable.bulb_on;
private static final int bulbOffImg = R.drawable.bulb_off;
private boolean state;
private Context context;
private int currentImage;
public LightImageButton(boolean state, Context context) {
this.state = state;
this.context = context;
currentImage = bulbOffImg;
}
public int getCurrentImage() {
return currentImage;
}
@Override
public void onClick(View v) {
ImageButton btn = (ImageButton) v;
if (state) {
currentImage = bulbOnImg;
} else {
currentImage = bulbOffImg;
}
state = !state;
btn.setBackground(context.getResources().getDrawable(currentImage));
}
}
但下一个结果是:
我想有正确的缩放图像。我怎么做?也许有什么更好的方法可以使用其他可单击类而不是ImageButton来实现这一点
# 1 楼答案
更改此项:
与: