Java 我的ImageButton没有像代码告诉它的那样重新缩放。事实上,它什么也没做

Java 我的ImageButton没有像代码告诉它的那样重新缩放。事实上,它什么也没做,java,android,Java,Android,我的ImageButton没有像代码告诉它的那样重新缩放。事实上,它什么也没做 代码: XML: 结果是这样的: 更改宽度和高度后,从FirstTimeB调用setLayoutParams。尝试使用android:src并更改ScaleType,看看这是否会使其缩放效果更好。 另外,在通过调用getLayoutParams设置宽度和高度后,您应该调用RequestLayout,否则将不会显示更改 如果要基于高度设置宽度,或者反之亦然,则应创建自己的自定义ImageButton类,该类包含以下代码

我的ImageButton没有像代码告诉它的那样重新缩放。事实上,它什么也没做

代码:

XML:

结果是这样的:


更改宽度和高度后,从FirstTimeB调用setLayoutParams。

尝试使用android:src并更改ScaleType,看看这是否会使其缩放效果更好。 另外,在通过调用getLayoutParams设置宽度和高度后,您应该调用RequestLayout,否则将不会显示更改

如果要基于高度设置宽度,或者反之亦然,则应创建自己的自定义ImageButton类,该类包含以下代码:

public class CustomImageButton extends ImageButton{

...

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);

int height = getMeasuredHeight();
float constant = 2.6666;
setMeasuredDimension(height * constant, height);
}

 ...

}
我想补充的是,我想知道你想做什么。我想不出一个senario需要屏幕大小来决定按钮的大小。试着重新思考你的方法,问问自己你所做的是否有意义。

试试这个:

public void getScreenRes(){
    DisplayMetrics display = this.getResources().getDisplayMetrics();
    int width = display.widthPixels;
    int height = display.heightPixels;
    int buttonheight = display.heightPixels / 8;
    double buttonwidth = buttonheight * 2.66666667;
    int buttonwidthint = (int) Math.round(buttonwidth);
    ImageButton firsttimeFB = (ImageButton) findViewById(R.id.firsttime_fb);
    LayoutParams lp = firsttimeFB.getLayoutParams();
    lp.width = buttonwidthint;
    lp.height = buttonheight;
    firsttimeFB.setLayoutParams(lp);

}

将android:background替换为android:srcim总是被告知要做相反的事情相同,唯一的区别是图像与图像按钮的宽度/高度不匹配,我想这样做,你到底想做什么?希望按钮的高度为屏幕大小的1/8,然后将宽度调整2.6667xHight,因为图像的宽高比是2.666667。是的,我也不明白他想做什么。我希望按钮的高度为屏幕大小的1/8,然后将宽度调整2.6667xHight,因为图像的宽高比是2.666667。现在无法更改代码,但明天将尝试此操作,thankspublic类CustomImageButton扩展了ImageButton{告诉我,'android.view.ImageButton'中没有可用的默认构造函数。您必须添加构造函数,转到错误并在android studio中按alt enter键,然后应该会出现解决方案。您还可以添加'public CustomImageButtonContext{supercontext;}公共CustomImageButtonContext上下文,属性集attrs{supercontext,attrs;}'
public void getScreenRes(){
    DisplayMetrics display = this.getResources().getDisplayMetrics();
    int width = display.widthPixels;
    int height = display.heightPixels;
    int buttonheight = display.heightPixels / 8;
    double buttonwidth = buttonheight * 2.66666667;
    int buttonwidthint = (int) Math.round(buttonwidth);
    ImageButton firsttimeFB = (ImageButton) findViewById(R.id.firsttime_fb);
    LayoutParams lp = firsttimeFB.getLayoutParams();
    lp.width = buttonwidthint;
    lp.height = buttonheight;
    firsttimeFB.setLayoutParams(lp);