AndroidDev
AndroidDev

Reputation: 1625

How to set view to be focusable in android tv app?

I am trying to create a custom layout for my android tv app rather than using fragments from leanback components. I have read in developer docs that in order to highlight the selected view, we need to set focusable and focusableInTouchMode to true. However this doesn't seem to work for me even though I have set these attributes.

What am I missing in this ?

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>

Upvotes: 2

Views: 2879

Answers (1)

burakk
burakk

Reputation: 1291

Buttons are focusable by default, so you don't need to set the android:focusable="true" and android:focusableInTouchMode="true" attributes. I don't see an id for the button. Just add an id to the button so that you can access it in the code and set the focus by calling the requestFocus method:

myButton.requestFocus();

Also, you should prepare the focused and unfocused states of the button by adding a selector xml file.

Upvotes: 2

Related Questions