Search code examples
androidviewfocusviewgroup

How to manually specified the next view id for a particular direction in android?


what is the method or config for manually specified the next view for a particular direction in android?

For Example I have three buttons:

button1 button2 button3

Normally, when I click right direction, I want to change focus from button1 to button2, then button3, but if I have a strange requirement:I want to change focus from button1 to button3, then chage to button2.

A more common requirement is that when the focus is in button3, I want change focus to button1 when right direction is clicked!

how can I meet these requirement?


Solution

  • Did you try android view's nextFocusRight/Left/Up/Down properties?

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:nextFocusRight="@+id/button2" />
    
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:nextFocusRight="@id/button1" />
    

    You can set these properties in Java code.

        Button button1 = (Button) findViewById(R.id.button1);
        Button button2 = (Button) findViewById(R.id.button2);
        Button button3 = (Button) findViewById(R.id.button3);
    
        button3.setNextFocusRightId(R.id.button1);