我在android中编写了一个自定义视图。当更改此视图的可见性时,我需要进行一些处理。是否有一些监听器在视图/窗口小部件的可见性发生变化时被调用?
编辑:
我知道如何更改可见性,想知道当我们在视图上设置可见性时是否有一个监听器!
答案 0 :(得分:16)
您想在自定义视图类中执行此处理吗? 如果是这样,为什么不覆盖setVisibility()方法,调用super(),然后进行自定义处理?
答案 1 :(得分:15)
我知道如何更改可见性,想知道是否有 在视图上设置可见性时调用的监听器!
您必须继承view/widget
并覆盖setVisibility
,并注册您将在其上重新发送通知的界面。例如:
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();
}
}
答案 2 :(得分:9)
您必须将要添加侦听器的视图子类化。然后,您应该覆盖onVisibilityChanged
而不是setVisibility
。当视图的可见性因任何原因(包括更改祖先视图时)发生变化时,会触发onVisibilityChanged
。
如果您希望在View
的可见性更改时通知其他班级,则需要一个界面。
示例:
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
// ...
}
}
答案 3 :(得分:-1)
要更改窗口小部件的可见性,请使用widget.setVisibility(View.Visible)
或widget.setVisibility(View.Invisible)
方法。