Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Need callback when View is shown

Tags:

android

view

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.

like image 378
Syed Fahad Sultan Avatar asked Jun 08 '12 11:06

Syed Fahad Sultan


1 Answers

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);
        }
    });
like image 127
Zelleriation Avatar answered Oct 02 '22 05:10

Zelleriation