0

I have an ImageView which has layout_width of fill_parent. I want to get the width of this ImageView in order to calculate the size of the thumbnail. The problem is that imageView.getWidth() and imageView.getHeight() both return 0 because the layout hasn't been sat yet.

My question is, does the ImageView has some kind of SizeChanged event or something of the kind? How do I react as soon as the ImageView width has been established?

Update:

I solved my problem this way. As I actually only needed the width of the ImageView which is set to fill_parent, what I actually needed was the device window size:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

int targetW = metrics.widthPixels;
Community
  • 1
  • 1
Ambran
  • 2,367
  • 4
  • 31
  • 46
  • I generally find it easiest to post a `Runnable` to the view's parent, like suggested in [this sample snippet](https://developer.android.com/training/gestures/viewgroup.html#delegate) from Google. That way the runnable is queued up in the parent's message queue, ensuring the logic it wraps isn't executed until the parent has laid out its children (which includes your target view). – MH. Mar 24 '15 at 16:37

2 Answers2

1

You can hook into a number of View tree events using a ViewTreeObserver. Specifically, either an OnGlobalLayoutListener or an OnPreDrawListener should work for you depending on what you are doing with the size.

Here's an example of using a ViewTreeObserverto get a View's width once everything has been laid out:

final ImageView myImageView = (ImageView) findViewById(R.id.image);
final ViewTreeObserver observer = myImageView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int height = myImageView.getHeight();
        // Do something with the height

        // Remove the layout listener so we don't waste time on future passes
        observer.removeOnGlobalLayoutListener(this);
    }
});
Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120
  • The observer.removeOnGlobalLayoutListener gave mig some problems as it only applies from api16 and up. Not removing it just causes inflation of events being fired when I only need one. I solved my problem much more simple. Answered in my post. – Ambran Mar 25 '15 at 15:56
0

According to this post's answer:

ImageView.getWidth() returns 0

You will need to call it from the following function:

public void onWindowFocusChanged(boolean hasFocus)

This is because the window has not yet been attached and as you have noticed your imageview will have no dimensions yet.

Community
  • 1
  • 1
JodiMiddleton
  • 310
  • 1
  • 8