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
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?
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
// ...
}
}
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();
}
}
To change the visibility of a widget, use the widget.setVisibility(View.Visible)
or widget.setVisibility(View.Invisible)
methods.