有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何以编程方式将图像适配到ImageButton

我正在尝试使用以下图像设置ImageButton的背景:enter image description here

和代码:

一旦创建:

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));
}
}

但下一个结果是: enter image description here

我想有正确的缩放图像。我怎么做?也许有什么更好的方法可以使用其他可单击类而不是ImageButton来实现这一点


共 (1) 个答案

  1. # 1 楼答案

    更改此项:

    imageButton.setBackground(getResources().getDrawable(lightImageButton.getCurrentImage()));
    

    与:

    imageButton.setImageResource(R.drawable.your_bulb);
    imageButton.setScaleType(ImageView.ScaleType.CENTER_CROP);
    

    enter image description here