监听器检测视图是否在前面?

时间:2017-05-25 10:13:48

标签: android focus android-view android-window

我有RecyclerView,在某些情况下,我会在其上显示另一个视图 - ProgressDialogAlertDialogDialogFragment

当我的RecyclerView在前面或其他视图现在位于其上时,是否有某种方法可以通知我?

我尝试将onFocusChangeListener()添加到RecyclerView,但没有运气。

PS。当然,我可以在RecyclerView中创建一些方法isOnFront(boolean onFront),并在我所有其他视图中调用它,但也许有更优雅的方式?

2 个答案:

答案 0 :(得分:2)

ProgressDialogAlertDialogDialogFragment会将内容放在Window到您的活动/片段的视图层次结构中。这意味着,只要显示其中任何一个,Window的焦点就会改变。因此,您可以使用ViewTreeObserver#addOnWindowFocusChangeListener() API:


    contentView.getViewTreeObserver().addOnWindowFocusChangeListener(
        new ViewTreeObserver.OnWindowFocusChangeListener() {
          @Override public void onWindowFocusChanged(boolean hasFocus) {
            // Remove observer when no longer needed
            // contentView.getViewTreeObserver().removeOnWindowFocusChangeListener(this);

            if (hasFocus) {
              // Your view hierarchy is in the front
            } else {
              // There is some other view on top of your view hierarchy,
              // which resulted in losing the focus of window
            }
          }
        });

答案 1 :(得分:1)

我认为您应该重新考虑您的软件设计。如果您触发对话框显示在另一个视图的顶部,那么您应该知道是否显示。另一个问题是:为什么您的RecyclerView会在您的申请中了解其他观点?

如果您真的想知道,如果您的对话框是否显示,请在显示时在Fragment(或Activity)中设置一个布尔变量。或者使用字段本身作为指标(myDialog != null等于“显示myDialog”)。如果您关闭对话框,请将其设置为null。如果您确实需要知道其他FragmentsViews,那么您可以使用任何类型的事件总线来播放此事件。

我不建议篡改任何类型的ViewTreeObserver侦听器或FragmentBackstack侦听器以获取此结果。