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


当前回答

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

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

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

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

希望对你使用充分。

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

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

demoImage.getLayoutParams().height = 150;

demoImage.getLayoutParams().width = 150;

demoImage.setScaleType(ImageView.ScaleType.FIT_XY);