Last Updated: February 25, 2016
·
9.325K
· munday

Focus on Android layout xml

The following four properties determine where the focus will go when leaving an element using non touchscreen pointing devices like Google TVs.

android:nextFocusUp="some_element_id"
android:nextFocusDown="some_element_id"
android:nextFocusLeft="some_element_id"
android:nextFocusRight="some_element_id"

To set default focus add

<requestFocus />

as a child of the element that you want focused by default. This works just like calling requestFocus() on a View subclass in code.

Simple example:

 <ImageButton
        android:id="@+id/list_icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerVertical="true"
        android:background="@drawable/button"
        android:contentDescription="@string/tooltip"
        android:scaleType="fitCenter"
        android:nextFocusUp="@+id/up_element"
        android:nextFocusDown="@+id/down_element"
        android:nextFocusLeft="@+id/left_element"
        android:nextFocusRight="@+id/right_element"
        android:src="@drawable/ic_action_list" >
        <requestFocus />
</ImageButton>