RJHP
RJHP

Reputation: 87

Android get imageview width and Height using OnPreDrawListener

I used OnPreDrawListener to get imageview width and Hieght it return correctly but i can't use outside of that method

in OnCreate:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawingarea);
    img=(ImageView)findViewById(R.id.imageView1);

    ViewTreeObserver vto = img.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {     
        public boolean onPreDraw(){
            // at this point, true width and height are already determined
          int width = img.getMeasuredWidth();
          int height = img.getMeasuredHeight();
          System.out.println(width);// it return value correctly
          System.out.println(height);//it return value correctly
            img.getViewTreeObserver().removeOnPreDrawListener(this);
            return false;
        }
    });
     System.out.println(width);// it return 0
     System.out.println(height);//it return 0
    }

How can i get the value outsite addOnPreDrawListener Please Help

Upvotes: 2

Views: 1015

Answers (1)

Gopal Gopi
Gopal Gopi

Reputation: 11131

declare your variables globally...

private int width;
private int height;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawingarea);
    img = (ImageView) findViewById(R.id.imageView1);

    ViewTreeObserver vto = img.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {
            // at this point, true width and height are already determined
            width = img.getMeasuredWidth();
            height = img.getMeasuredHeight();
            System.out.println(width);// it return value correctly
            System.out.println(height);// it return value correctly
            img.getViewTreeObserver().removeOnPreDrawListener(this);
            return false;
        }
    });
    System.out.println(width);// it return 0
    System.out.println(height);// it return 0
}

and you are getting correct values in onCreate(), I mean width and height will be zero in onCreate() as drawing of your ImageView is not performed yet... you can check those values in onWindowFocusChanged(). and your onPreDrawListener callback will be invoked at the the time of Drawing width and height values will be correct as ImageView has measured and layouted just before drawing...

Upvotes: 4

Related Questions