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


当前回答

科特林

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

其他回答

int newHeight = 150;
            int newWidth = 150; 
            holder.iv_arrow.requestLayout();
            holder.iv_arrow.getLayoutParams().height = newHeight;
            holder.iv_arrow.getLayoutParams().width = newWidth;
            holder.iv_arrow.setScaleType(ImageView.ScaleType.FIT_XY);
            holder.iv_arrow.setImageResource(R.drawable.video_menu);

科特林

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

如果你需要将你的宽度或高度设置为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;
//...

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

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

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

希望这对你有所帮助。