15

我在android中编写了一个自定义视图。当此视图的可见性发生更改时,我需要进行一些处理。当视图/小部件的可见性改变时,是否有一些监听器被调用?

编辑:

我知道如何改变可见性,想知道当我们在视图上设置可见性时是否有一个监听器被调用!

4

4 回答 4

18

您想在自定义视图类中进行该处理吗?如果是这样,那为什么不直接重写 setVisibility() 方法,调用 super(),然后进行自定义处理呢?

于 2013-05-08T14:30:27.333 回答
17

我知道如何改变可见性,想知道当我们在视图上设置可见性时是否有一个监听器被调用!

您必须继承 yourview/widget和 override 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();
 }

}
于 2013-05-08T14:37:16.300 回答
13

您必须对要添加侦听器的视图进行子类化。然后,您应该覆盖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
   // ...
 }
}
于 2015-03-19T17:01:43.650 回答
-1

要更改小部件的可见性,请使用widget.setVisibility(View.Visible)orwidget.setVisibility(View.Invisible)方法。

于 2013-05-08T14:19:33.153 回答