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


当前回答

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

imageView.getLayoutParams().height = 20;

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

imageView.requestLayout();

其他回答

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

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

的形象。setLayoutParams(新ViewGroup。LayoutParams(宽度、高度));

例子:

image.setLayoutParams(new ViewGroup.LayoutParams(150, 150));
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和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);

以下是完成任务的简单方法:

setContentView(R.id.main);    
ImageView iv = (ImageView) findViewById(R.id.left);
int width = 60;
int height = 60;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(parms);

另一种方法是,如果你想要给出屏幕的高度和宽度,那么使用下面的代码:

setContentView(R.id.main);    
Display display = getWindowManager().getDefaultDisplay();
ImageView iv = (LinearLayout) findViewById(R.id.left);
int width = display.getWidth(); // ((display.getWidth()*20)/100)
int height = display.getHeight();// ((display.getHeight()*30)/100)
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(parms);

希望对你使用充分。