如何将设计支持库与 Leanback 一起用于 android 电视?

How to use design support library together with leanback for android TV?

我有 android 电视应用程序的定制设计,并非所有设计都与 Leanback 库中的小部件匹配。 如何使用设计支持库(例如 TabLayout)? 它抱怨我需要使用 AppCompat 主题。 我知道 google 不建议在电视上使用标签。

要在 Leanback 应用程序中创建 TabLayout,您可以使用 ContextThemeWrapper(我用 Kotlin 编写了这个):

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
    val c = ContextThemeWrapper(activity, R.style.Theme_AppCompat)
    return LayoutInflater.from(c).inflate(R.layout.my_tablayout, container, false)
}

为了让 DPAD 正常工作,我将 TabLayout 子类化如下:

class FocusableTabLayout(context: Context, attributeSet: AttributeSet): TabLayout(context, attributeSet) {
    override fun focusSearch(focused: View?, direction: Int): View? {
        val view = super.focusSearch(focused, direction)
        if (hasFocus() && view != null) {
            if (direction == View.FOCUS_LEFT) {
                if (selectedTabPosition > 0) {
                    getTabAt(selectedTabPosition - 1)?.select()
                }
            } else if (direction == View.FOCUS_RIGHT) {
                if (selectedTabPosition < tabCount) {
                    getTabAt(selectedTabPosition + 1)?.select()
                }
            }
        }
        return view
    }

    override fun requestFocus(direction: Int, previouslyFocusedRect: Rect?): Boolean {
        val tabStrip = getChildAt(0) as LinearLayout
        tabStrip.getChildAt(selectedTabPosition).requestFocus()
        return true
    }
}

如果您打算将 TabLayoutViewPager 一起使用,请使用此子类来防止一页上的 DPAD 交互触发幻灯片:

class FocusableViewPager(context: Context, attributeSet: AttributeSet): ViewPager(context, attributeSet) {
    override fun executeKeyEvent(event: KeyEvent): Boolean {
        return false
    }
}

TabLayout Focus 不能与 D-PAD(电视应用程序)一起使用。 我使用了 app:tabMode="scrollable" 属性 我在没有 viewpager 的情况下使用了 20 个选项卡项。