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


当前回答

我用像素和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();

希望这对你有所帮助。

其他回答

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

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

如果你只是想在图像视图中适合图像,你可以使用缩放类型的高度和宽度属性“包装内容”,但如果你想手动设置,你必须使用LayoutParams。

Layoutparams对于以编程方式设置布局高度和宽度非常有效。

为了以编程方式设置ImageView和Height,你可以这样做

            //Makesure you calculate the density pixel and multiply it with the size of width/height
            float dpCalculation = getResources().getDisplayMetrics().density;
            your_imageview.getLayoutParams().width = (int) (150 * dpCalculation);

            //Set ScaleType according to your choice...
            your_imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
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 ;

这可能太迟了,但为了其他人有同样的问题,设置ImageView的高度:

imageView.getLayoutParams().height = 20;

重要的。如果你在布局已经“布局”之后设置高度,确保你还调用:

imageView.requestLayout();