我如何设置一个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;
//...

其他回答

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

imageView.getLayoutParams().height = 20;

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

imageView.requestLayout();

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

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

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

为要添加该视图的布局设置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);

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

您可以为所有情况设置值。

demoImage.getLayoutParams().height = 150;

demoImage.getLayoutParams().width = 150;

demoImage.setScaleType(ImageView.ScaleType.FIT_XY);