How to handle visibility changes for a custom android view/widget

前端 未结 4 2028
感情败类
感情败类 2021-01-04 05:09

I have written a custom view in android. I need to do some processing when visibility of this view is changed. Is there some listener which is called when visibility of a vi

4条回答
  •  灰色年华
    2021-01-04 05:53

    You have to subclass the view you want to add a listener to. You then should override onVisibilityChanged instead of setVisibility. onVisibilityChanged is triggered when the view's visibility is changed for any reason, including when an ancestor view was changed.

    You will need an interface if you want a different class to be notified when your View's visibility changes.

    Example:

    public class MyView extends View {
      private OnVisibilityChangedListener mVisibilityListener;
    
      public interface OnVisibilityChangedListener {
        // Avoid "onVisibilityChanged" name because it's a View method
        public void visibilityChanged(int visibility);
      }
    
      public void setVisibilityListener(OnVisibilityChangedListener listener) {
        this.mVisibilityListener = listener;
      }
    
     protected void onVisibilityChanged (View view, int visibility) {
       super.onVisibilityChanged(view, visibility);
    
       // if view == this then this view was directly changed.
       // Otherwise, it was an ancestor that was changed.
    
       // Notify external listener
       if (mVisibilityListener != null)
         mVisibilityListener.visibilityChanged(visibility);
    
       // Now we can do some things of our own down here
       // ...
     }
    }
    

提交回复
热议问题