2

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>
AndroidDev
  • 1,485
  • 2
  • 18
  • 33
  • Is button_bg a StateListDrawable? You shouldn't need to set the focusable or focusableInTouchMode properties since Buttons are focusable by default. – Ian G. Clifton Jun 07 '21 at 23:28
  • @IanG.Clifton, Yes I was aware of the default values of focusable and focusableInTouchMode, even without that it didn't work. And Yes button_bg is stateListDrawable, have updated the qn with that code. – AndroidDev Jun 08 '21 at 04:43

1 Answers1

2

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.

burakk
  • 1,231
  • 2
  • 22
  • 45
  • I have added the stateListDrawable xml and I did try without setting focusable and focusableInTouchMode, it didn't work. – AndroidDev Jun 08 '21 at 04:51
  • 1
    How are you trying to set the focus on the button? Please share the relevant code. – burakk Jun 08 '21 at 10:54