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


当前回答

为了以编程方式设置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);

其他回答

简单地创建一个LayoutParams对象并将其分配给imageView

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(150, 150);
imageView.setLayoutParams(params);

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

imageView.getLayoutParams().height = 20;

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

imageView.requestLayout();

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

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

如果图像视图是动态的,则包含getLayout的答案将失败,并出现空异常。

在这种情况下,正确的方法是:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100);
iv.setLayoutParams(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);