如何知道片段是否可见?

新手上路,请多包涵

我正在使用支持库 v4,我的问题是,如何知道片段是否可见?以及如何更改片段中膨胀的布局的属性?提前致谢。

- -编辑 - -

我正在使用带有 FragmentActivity 的 android 开发人员教程中的片段

原文由 Poperto Arcadio Buendía 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 399
2 个回答

您应该能够执行以下操作:

 MyFragmentClass test = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("testID");
if (test != null && test.isVisible()) {
     //DO STUFF
}
else {
    //Whatever
}

原文由 TronicZomB 发布,翻译遵循 CC BY-SA 3.0 许可协议

getUserVisibleHint 现在已被弃用,当另一个片段是 add 时,我遇到了问题 isVisible 是真的。这会使用其视图检测片段在后台堆栈上的可见性。如果您的问题与后台堆栈上的其他片段有关,这可能会有所帮助。

用于检测屏幕上是否正在显示视图的视图扩展:(另请参阅 How can you tell if a View is visible on screen in Android?

 fun View.isVisibleOnScreen(): Boolean {
    if (!isShown) return false
    val actualPosition = Rect().also { getGlobalVisibleRect(it) }
    val screenWidth = Resources.getSystem().displayMetrics.widthPixels
    val screenHeight = Resources.getSystem().displayMetrics.heightPixels
    val screen = Rect(0, 0, screenWidth, screenHeight)
    return Rect.intersects(actualPosition, screen)
}

然后从fragment中定义了一个back stack listener,观察栈顶的fragment(最后添加的那个)

 fun Fragment.setOnFragmentStackVisibilityListener(onVisible: () -> Unit) {
    val renderDelayMillis = 300L
    parentFragmentManager.addOnBackStackChangedListener {
        Handler(Looper.getMainLooper()).postDelayed({
            if (isAdded) {
                val topStackFragment = parentFragmentManager.fragments[parentFragmentManager.fragments.size - 1]
                if (topStackFragment.view == view && isVisible && view!!.isVisibleOnScreen()) {
                    onVisible.invoke()
                }
            }
        }, renderDelayMillis)
    }
}

在视图准备好之前调用返回堆栈侦听器,因此需要任意小的延迟。当视图可见时调用 lambda。

原文由 Kabliz 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题