Manage view visibility changes without overriding views

Is there a way to handle changing the visibility of a view (say, from GONE to VISIBLE) without overriding the view?

Something like View.setOnVisibilityChangeListener(); ?

+7
android
source share
3 answers

You can use the GlobalLayoutListener to determine if there are any changes to the visibility of the views.

 myView.setTag(myView.getVisibility()); myView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int newVis = myView.getVisibility(); if((int)myView.getTag() != newVis) { myView.setTag(myView.getVisibility()); //visibility has changed } } }); 
+26
source share

Instead of subclassing you can use decoration:

 class WatchedView { static class Listener { void onVisibilityChanged(int visibility); } private View v; private Listener listener; WatchedView(View v) { this.v = v; } void setListener(Listener l) { this.listener = l; } public setVisibility(int visibility) { v.setVisibility(visibility); if(listener != null) { listener.onVisibilityChanged(visibility); } } } 

Then

  WatchedView v = new WatchedView(findViewById(R.id.myview)); v.setListener(this); 
+3
source share

Take a look at ViewTreeObserver.OnGlobalLayoutListener . As stated in the documentation, its onGlobalLayout() callback method is called when the global layout state or the visibility of the views in the view tree changes. Therefore, you can try to use it to detect changes in view visibility.

+2
source share

All Articles