Set ImageView width and height programmatically?
It may be too late but for the sake of others who have the same problem, to set the height of the ImageView
:
imageView.getLayoutParams().height = 20;
Important. If you're setting the height after the layout has already been 'laid out', make sure you also call:
imageView.requestLayout();
If your image view is dynamic, the answer containing getLayout will fail with null-exception.
In that case the correct way is:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100);
iv.setLayoutParams(layoutParams);
This simple way to do your task:
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);
and another way if you want to give screen size in height and width then use below code :
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);
hope use full to you.
I have played this one with pixel
and dp
.
private int dimensionInPixel = 200;
How to set by pixel:
view.getLayoutParams().height = dimensionInPixel;
view.getLayoutParams().width = dimensionInPixel;
view.requestLayout();
How to set by dp:
int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
view.getLayoutParams().height = dimensionInDp;
view.getLayoutParams().width = dimensionInDp;
view.requestLayout();
Hope this would help you.