当片段位于另一个片段之上时焦点丢失

Joh*_*996 5 android android-fragments

用于理解问题的图像

大家好。我有一个片段 A。从那里我添加了片段 B,.add()因为我想将片段 A 作为背景。到目前为止一切都很好。问题是,我可以focus out使用 Fragments B recyclerview 项目并在 Fragment A 中导航 - 我想避免这种情况。有解决办法吗?如果是这样,如何?有没有办法禁用片段 A 的可聚焦性?

我试过这样的事情(伪代码)

活动“X”:

onBackStackChange 
    if fragment B is on top {
        fragment A.getView.setFocusability = false;
    }
Run Code Online (Sandbox Code Playgroud)

还有其他想法吗?

PS 这实际上是在 Android TV 上使用 Leanback 库。可能有一种解决方案可以使用内置的leanback 禁用对片段A 的关注,但我很确定还有其他标准的方法可以做到这一点。

关于卡片视图 - https://developer.android.com/training/tv/playback/card.html

Edu*_*ard 1

我遇到了完全相同的问题,并且发现了这个重复项:Disable focus onfragment

接受的解决方案对我有用。

这是迄今为止我的实现版本(可以改进):

abstract class BaseFragment<....> : Fragment() {

    private val screenFocusHelper = ScreenFocusHelper()

    fun enableFocus() {
        if (view != null) {
            // Enable focus
            screenFocusHelper.setEnableView(view as ViewGroup, true)

            // Clear focusable elements
            screenFocusHelper.focusableViews.clear()
        }

        childFragmentManager.fragments.forEach {
            if (it is BaseFragment<*, *>) {
                it.enableFocus()
            }
        }
    }

    fun disableFocus() {
        if (view != null) {
            // Store last focused element
            screenFocusHelper.previousFocus = view?.findFocus()

            // Clear current focus
            view!!.clearFocus()

            // Disable focus
            screenFocusHelper.setEnableView(view as ViewGroup, false)
        }

        childFragmentManager.fragments.forEach {
            if (it is BaseFragment<*, *>) {
                it.disableFocus()
            }
        }
    }

}

class ScreenFocusHelper {

    var previousFocus: View? = null

    val focusableViews: MutableList<View> = mutableListOf()

    fun setEnableView(viewGroup: ViewGroup, isEnabled: Boolean) {
        findFocusableViews(viewGroup)

        for (view in focusableViews) {
            view.isEnabled = isEnabled
            view.isFocusable = isEnabled
        }
    }

    private fun findFocusableViews(viewGroup: ViewGroup) {
        val childCount = viewGroup.childCount
        for (i in 0 until childCount) {
            val view = viewGroup.getChildAt(i)
            if (view.isFocusable) {
                if (!focusableViews.contains(view)) {
                    focusableViews += view
                }
            }
            if (view is ViewGroup) {
                findFocusableViews(view)
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)