Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle a view visibility change without overriding the view

Tags:

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

Something like View.setOnVisibilityChangeListener();?

like image 349
Federico Ponzi Avatar asked Sep 25 '15 08:09

Federico Ponzi


2 Answers

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
        }
    }
});
like image 191
Nicolas Tyler Avatar answered Oct 12 '22 23:10

Nicolas Tyler


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);
like image 35
Alexander Kulyakhtin Avatar answered Oct 12 '22 22:10

Alexander Kulyakhtin