我如何设置一个ImageView的宽度和高度编程?


当前回答

如果你需要将你的宽度或高度设置为match_parent(与其父类一样大)或wrap_content(大到足以适合它自己的内部内容),那么ViewGroup。LayoutParams有两个常量:

imageView.setLayoutParams(
    new ViewGroup.LayoutParams(
        // or ViewGroup.LayoutParams.WRAP_CONTENT
        ViewGroup.LayoutParams.MATCH_PARENT,      
        // or ViewGroup.LayoutParams.WRAP_CONTENT,     
        ViewGroup.LayoutParams.MATCH_PARENT ) );

或者你也可以像哈基姆·扎伊德的回答那样

imageView.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
//...

其他回答

在需要以编程方式设置小部件大小的场景中,请确保遵守以下规则。

为要添加该视图的布局设置LayoutParam。在我的情况下,我添加到TableRow,所以我必须做TableRow。LayoutParams 遵循以下代码

final float scale = getResources().getDisplayMetrics().density; int dpWidthInPx = (int) (17 * scale); int dpHeightInPx = (int) (17 * scale);

TableRow。LayoutParams deletelayoutParams = new table。LayoutParams (dpWidthInPx dpHeightInPx); button.setLayoutParams (deletelayoutParams); tableRow。addView(按钮,1);

科特林

val density = Resources.getSystem().displayMetrics.density
view.layoutParams.height = 20 * density.toInt()

动态设置按钮的最佳和最简单的方法是

 Button index=new Button(this);
 int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics());             
 int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 42, getResources().getDisplayMetrics());

上面的高度和宽度以像素为单位px。45是dp的高42是dp的宽。

 index.setLayoutParams(new <Parent>.LayoutParams(width, height));

例如,如果你把你的按钮放在一个tableerow中在一个tableelayout中,你应该把它作为TableRow。LayoutParams

 index.setLayoutParams(new TableRow.LayoutParams(width, height));

我用像素和dp做了这个。

private int dimensionInPixel = 200;

如何按像素设置:

view.getLayoutParams().height = dimensionInPixel;
view.getLayoutParams().width = dimensionInPixel;
view.requestLayout();

dp设置方法:

int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
view.getLayoutParams().height = dimensionInDp;
view.getLayoutParams().width = dimensionInDp;
view.requestLayout();

希望这对你有所帮助。

image_view.getLayoutParams().height 

返回以像素为单位的高度值。您需要首先获取屏幕尺寸以正确设置值。

 Display display = context.getWindowManager().getDefaultDisplay();
 DisplayMetrics outMetrics = new DisplayMetrics();
 display.getMetrics(outMetrics);
 int screen_height = outMetrics.heightPixels;
 int screen_width = outMetrics.widthPixels;

在你得到屏幕尺寸后,你可以设置imageview的宽度和高度使用适当的边距。

 view.getLayoutParams().height = screen_height - 140;
 view.getLayoutParams().width = screen_width - 130 ;