Federico Ponzi Federico Ponzi - 11 days ago 5
Android Question

Handle a view visibility change without overriding the view

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

Something like

View.setOnVisibilityChangeListener();
?

Answer

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

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
        }
    }
});
Comments