0

I want to get width and height of ImageView.

myimgbg = (ImageView) findViewById(R.id.myimggb); myimgbg.setBackgroundResource(R.drawable.dudu_1); 
3
  • what about View.getWidth() and View.getHeight()? Commented Jan 8, 2014 at 3:29
  • I do, but returns 0..why?..help Commented Jan 8, 2014 at 3:35
  • have you solved your problem or not? Commented Jan 8, 2014 at 3:50

6 Answers 6

2

The other answers demonstrate how to get the dimensions, but you are trying to do it too early, before the layout has been measured. This is how you do this but I am pretty sure you should never need to do this - there is almost always a better way that does not require you to know the pixel dimensions of anything.

myimgbg.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { myimgbg.getViewTreeObserver().removeGlobalOnLayoutListener(this); int width = myimgbg.getWidth(); } }); 

Just to emphasize again, if you are doing something that requires knowing the exact pixel size of a view, you should probably take a step back and reconsider how to do what you want.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks!!.. I want to get the value with int width; myimgbg.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { myimgbg.getViewTreeObserver().removeGlobalOnLayoutListener(this); width = myimgbg.getWidth(); } }); Log.e("with",with+"");
The problem is the width is just not available when you run this code. You have to wait for the callback after the measurement has occurred. Put any code that depends on width (i.e., your log statement) inside the onGlobalLayout()
1

Check this :

image_view.getLayoutParams().height image_view.getLayoutParams().width 

Hope this helps.

Comments

0

try myimgbg.getWidth() and myimgbg.getHeight()

2 Comments

I do, but returns 0..why?..help
u'll get the width and height only after adding image to the imageview (if u've set wrapcontent for width and height to imageview in xml)..
0

This is simple way to get width and height from imageview

ImageView img = (ImageView) findViewById(R.id.img); Log.d(TAG, "width : " + img.getWidth()); 

Comments

0

Just try, after your view is drawn

 yourView.getHeight() yourView.getWidth() 

or

LayoutParams params=yourView.getLayoutParams(); params.height //is your views height 

1 Comment

I do, but returns 0..why?..help
0

Try this:

int width=image.getWidth(); int Height=image.getHeight(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.