【问题标题】:How to set view to be focusable in android tv app?如何在 android tv 应用程序中将视图设置为可聚焦?
【发布时间】:2021-06-07 17:28:35
【问题描述】:

我正在尝试为我的 android 电视应用程序创建自定义布局,而不是使用来自 Leanback 组件的片段。我在开发人员文档中读到,为了突出显示选定的视图,我们需要将 focusable 和 focusableInTouchMode 设置为 true。 然而,即使我已经设置了这些属性,这似乎对我不起作用。

我错过了什么?

activity_video.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.leanback.tab.LeanbackViewPager
        android:id="@+id/bubbleViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:background="@drawable/button_bg"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginBottom="16dp"
        android:layout_marginStart="16dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

button_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/white" android:state_selected="true"/>
    <item android:drawable="@android:color/transparent" android:state_selected="false" />

</selector>

【问题讨论】:

  • button_bg 是 StateListDrawable 吗?您不需要设置 focusable 或 focusableInTouchMode 属性,因为默认情况下按钮是可聚焦的。
  • @IanG.Clifton,是的,我知道 focusable 和 focusableInTouchMode 的默认值,即使没有它也不起作用。是的 button_bg 是 stateListDrawable,已经用该代码更新了 qn。

标签: android android-tv leanback


【解决方案1】:

默认情况下按钮是可聚焦的,因此您无需设置android:focusable="true"android:focusableInTouchMode="true" 属性。我没有看到按钮的 ID。只需给按钮添加一个 id 以便您可以在代码中访问它并通过调用 requestFocus 方法设置焦点:

myButton.requestFocus();

此外,您应该通过添加选择器 xml 文件来准备按钮的焦点和非焦点状态。

【讨论】:

  • 我已经添加了 stateListDrawable xml,但我没有设置 focusable 和 focusableInTouchMode,但没有成功。
  • 您如何尝试将焦点设置在按钮上?请分享相关代码。
猜你喜欢
  • 2015-12-15
  • 2018-03-29
  • 1970-01-01
  • 2014-09-28
  • 2018-01-18
  • 1970-01-01
  • 1970-01-01
  • 2011-02-14
  • 1970-01-01
相关资源
最近更新 更多