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

前端 未结 4 1998
感情败类
感情败类 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:52

    Do you want to do that processing within your custom view class? If so, then why not just override the setVisibility() method, call super(), and then do your custom processing?

    0 讨论(0)
  • 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
       // ...
     }
    }
    
    0 讨论(0)
  • 2021-01-04 06:09

    I know how to change the visibility, would like to know if there is a listener which is called when we setVisibility on the view!

    you have to subclass your view/widget and override setVisibility, and register a interface on which you will recive the notification. For instance:

    public class MyView extends View {
    
      public interface MyListener {
        public void onSetVisibilityCalled();
      }
    
      public void registerListener(MyListener myListener) {
        this.mListener = myListener;
      }
    
     public void setVisibility (int visibility) {
       super.setVisibility(visibility);
       if (mListener != null)
         mListener.onSetVisibilityCalled();
     }
    
    }
    
    0 讨论(0)
  • 2021-01-04 06:11

    To change the visibility of a widget, use the widget.setVisibility(View.Visible) or widget.setVisibility(View.Invisible) methods.

    0 讨论(0)
提交回复
热议问题