Android - listener for View's Visibility updates

     Android View implementations don't provide a callback mechanism for changes to a view's visibility. The closest callback is a hook API onVisibilityChanged that custom implementation can override. However, this doesn't really help for application components using direct SDK View components and i had to live this workaround, which is sadly too much of a work.

public class MyImageView extends ImageView {

    WeakReference<VisibilityChangeListener> mListener;

    public interface VisibilityChangeListener {
        public void onVisibilityChanged(int visibility);
    }

    public MyImageView(Context context) {
        super(context);
    }

    public MyImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setVisibilityChangeListener(VisibilityChangeListener listener) {
        mListener = new WeakReference<VisibilityChangeListener>(listener);
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);

        if (mListener != null && changedView == this) {
            VisibilityChangeListener listener = mListener.get();
            if (listener != null) {
                listener.onVisibilityChanged(visibility);
            }
        }

    }

No comments: