Android – Need callback when View is shown

androidview

Is there a method equivalent to Dialog.setOnShowListener() for the View class in android ?

I need it because when I call getLocationOnScreen on a View (say foo) in the line immediately following someViewGroup.addView(foo), I get location = (0,0).

I cannot use any lifecycle method of the activity, because addition of foo is on run (press of a button). Any help would be highly appreciated. Thanks in advance.

Best Answer

You should use a ViewTreeObserver:

someViewGroup.addView(foo)    

ViewTreeObserver vto = someViewGroup.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

            ///getLocationOnScreen here

            ViewTreeObserver obs = someViewGroup.getViewTreeObserver();
            obs.removeGlobalOnLayoutListener(this);
        }
    });