Image for understanding of problem
大家好。我有一个片段A.从那里我添加片段B与.add()
,因为我想看到片段A作为背景。到目前为止一切都还好。问题是,我可以focus out
片段B回收物品项目并在片段A中导航 - 我想避免。有解决方案吗?如果是这样,怎么样?有没有办法在Fragment A上禁用焦点?
我试过这样的事情(伪代码)
活动" X":
onBackStackChange
if fragment B is on top {
fragment A.getView.setFocusability = false;
}
还有其他想法吗?
P.S。这实际上是在使用Leanback库的Android TV上。可能有一个解决方案可以使用leanback内置函数进行路径并禁用对Fragment A的关注,但我非常确定还有其他标准的方法。
关于卡片视图 - https://developer.android.com/training/tv/playback/card.html
答案 0 :(得分:0)
我遇到了完全相同的问题,并且发现了以下重复项:Disable focus on fragment
可接受的解决方案对我有用。
这是我到目前为止的实现版本(可以改进):
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)
}
}
}
}