Android 在代码中设置图像按钮的高度和宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10992241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:40:28  来源:igfitidea点击:

set imagebutton height and width in code

android

提问by imin

this is my code

这是我的代码

ImageButton btnPlayVideo = (ImageButton) findViewById(R.id.btnPlayVideo);
btnPlayVideo.setBackgroundResource(R.drawable.play_icon_grey);
btnPlayVideo.setAdjustViewBounds(true);
btnPlayVideo.setMaxHeight(10);
btnPlayVideo.setMaxWidth(10);

and in my xml

在我的 xml 中

<ImageButton
android:id="@+id/btnPlayVideo"
android:layout_width="90dp"
android:layout_height="90dp"
android:background="@android:color/transparent"
android:layout_span="2" />

but it seems the setmaxheight and layout_height and width doesn't even work. so how do i set the imagebutton's dimension?

但似乎 setmaxheight 和 layout_height 和宽度甚至不起作用。那么如何设置图像按钮的尺寸?

回答by Vipul Shah

You will need to use android:scaleTypeto have it resize to fit.

您将需要使用android:scaleType它来调整大小以适应。

<ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/ic_launcher"
        android:scaleType="fitXY" />

Which produces following output.

产生以下输出。

enter image description here

在此处输入图片说明

回答by Fenix Voltres

You can do it from code via

您可以通过代码通过

android.view.ViewGroup.LayoutParams params = btnPlayVideo.getLayoutParams();
params.height = myHeight;
params.width = myWidth;
btnPlayVideo.setLayoutParams(params);

, but probably your problem lays not in the code, but in layout - I see you are using android:layout_span="2"- does that mean btnPlayVideois in TableLayout? If so, you must regulate this TableLayout's dimensions, because its children will always have fill_parentwidth and heights.

,但可能你的问题不在于代码,而在于布局——我看到你正在使用android:layout_span="2"——这是否意味着btnPlayVideoTableLayout?如果是这样,您必须调节 thisTableLayout的尺寸,因为它的子项将始终具有fill_parent宽度和高度。

回答by Bonne Bogaert

I used metrics:

我使用了指标:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

btnPlayVideo.setMinimumHeight(metrics.heightPixels / (amount));
btnPlayVideo.setMinimumWidth(metrics.widthPixels/ (amount));