1
<LinearLayout
            android:id="@+id/loginInputs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <EditText
                android:id="@+id/txtUsername"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:ems="10"
                android:hint="User Name"
                android:imeOptions="actionNext"
                android:text="" />

            <EditText
                android:id="@+id/txtPassword"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:ems="10"
                android:inputType="textPassword"
                android:text="" />
        </LinearLayout>

I want to get the next focus of txtUsername in code. If I set the android:nextFocusDown attribute, I can get it by using txtUsername.getNextFocusDownId();. ( When softkey enter pressed focus moved to nextFocusDown) I want to know that is there any method to get the default next focus by code without setting focus attributes.

I can get the same functionality by setting focus attributes to all the EditTexts. But I feel there should be a better way of doing it.

P.W. I want to do some logic according to the next focus. I don't want to change the focus.

  • _"But I feel there should be a better way of doing it"_ Are you suggesting that manually fielding and adjusting focus at runtime is better than defining focus attributes in XML? – CzarMatt Aug 08 '17 at 18:38
  • @CzarMatt No. For an existing project, defining focus attributes for all the EditText is time consuming. Only when the focus attributes are set, I can get the next focus by code. But not other way around. – Sameera Nandasiri Aug 08 '17 at 18:44

1 Answers1

0

Based on your P.W. and your question comment, I would recommend using View.OnFocusChangeListener

https://developer.android.com/reference/android/view/View.OnFocusChangeListener.html

Attach a listener to your EditText (or any other view in your hierarchy that could receive focus)

txtUsername.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus)
            // do some logic here, removing focus if necessary
    }
});

This way, you can field for focus change events and handle any additional logic you want to perform. You can also remove focus from this object and set it elsewhere if you wish.

Android will do its best to direct focus, but it isn't perfect when focus attributes aren't defined. It is our job as developers to fill in the gaps and create the best navigation experience.

See Making Apps More Accessible for more information.

CzarMatt
  • 1,773
  • 18
  • 22