Android - callback required when displaying a view

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

I need this because when I call getLocationOnScreen in the view (say foo) in the line right after someViewGroup.addView (foo), I get location = (0,0).

I cannot use any activity lifecycle because adding foo is enabled (button click). Any help would be greatly appreciated. Thanks in advance.

+8
android view
source share
1 answer

You should use 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); } }); 
+17
source share

All Articles