Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageView.getWidth() returns 0

Tags:

I get imageView's width 0. Below is code.

xml file :

<ImageView         android:id="@+id/img"         android:layout_width="200dp"         android:layout_height="200dp" /> 

Activity :

@Override protected void onResume() {     super.onResume();     ImageView img = (ImageView) findViewById(R.id.img);     Log.d(TAG, "width : " + img.getWidth()); } 

I don't want to use below code as I need to place this code in so many places.

ViewTreeObserver vto = img.getViewTreeObserver();     vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {         public boolean onPreDraw() {             ImageView img = (ImageView) findViewById(R.id.img);                     Log.d(TAG, "width : " + img.getWidth());             return true;         }     }); 

My workaround : I actually later did not need to add this code in an activity. I added it to a non-activity class and instead of ImageView's width I used Bitmap image's width and now does not have this problem.

like image 554
Geek Avatar asked Oct 09 '13 12:10

Geek


People also ask

How do you find the height of a view?

You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.

How do you find the height and width of a view?

The width and height can be obtained by calling getWidth() and getHeight().

What is ImageView code?

Displays image resources, for example Bitmap or Drawable resources. ImageView is also commonly used to apply tints to an image and handle image scaling. To learn more about Drawables, see: Drawable Resources.


1 Answers

Where you calling getWidth() and getHeight() on ImageView? If you calling from onCreate() in activity, it won't work. You need to wait for activity window to attached and then call getWidth() and getHeight() on ImageView. You can try calling getWidth() and getHeight() from onWindowFocusChanged() method of your activity.

call on onWindowFocusChanged like this way

public void onWindowFocusChanged(boolean hasFocus) {     // TODO Auto-generated method stub     super.onWindowFocusChanged(hasFocus);      if (hasFocus) {         ImageView img = (ImageView) findViewById(R.id.img);         Log.d(TAG, "width : " + img.getWidth());      }      } 
like image 119
Sanket Kachhela Avatar answered Sep 19 '22 19:09

Sanket Kachhela