1
private void getPicDetails() {

            targetW = img_cow.getWidth();
            targetH = img_cow.getHeight();

            Log.e("targetW: ", "" + targetW);
            Log.e("targetH: ", "" + targetH); 
        }

I have an image view and the method above gets the height and width to print the values of height and width. Now when I call getPicDetails() in onCreate, the values are 0, same as when I put it in OnStart and onResume.

My question is: where should I put my method such that the imageview is initialized and exists?

marsei
  • 7,691
  • 3
  • 32
  • 41
Operative
  • 149
  • 1
  • 2
  • 10

3 Answers3

2

you can call inside the onWindowFocusChanged

@Override
public void onWindowFocusChanged(boolean hasFocus){
    int width=imageView.getWidth();
    int height=imageView.getHeight();
}
Aerrow
  • 12,086
  • 10
  • 56
  • 90
0

where in the lifecycle of my android app should i get width and height of image view

After layout is complete:

@Override
public void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    getPicDetails();
}
Caner
  • 57,267
  • 35
  • 174
  • 180
0

you can use the next function i've made:

  public static void runJustBeforeBeingDrawn(View view, Runnable runnable)
  {
    ViewTreeObserver.OnPreDrawListener preDrawListener = new ViewTreeObserver.OnPreDrawListener(view, runnable)
    {
      public boolean onPreDraw() {
        ViewUtil.this.getViewTreeObserver().removeOnPreDrawListener(this);
        runnable.run();
        return true;
      }
    };
    view.getViewTreeObserver().addOnPreDrawListener(preDrawListener);
  } 

EDIT: Alternative to runJustBeforeBeingDrawn: https://stackoverflow.com/a/28136027/878126

android developer
  • 114,585
  • 152
  • 739
  • 1,270