Search code examples
javaandroidfocussetfocusimeoptions

Retaining focus on Edittext within OnFocusChanged Listener


I am trying to set up a system to validate user input, in this case, just checking that there is anything entered by the user.

I have a Utility class that checks that the EditText has data.

I am using an OnFocusChangeListener which then calls the method from the Utility class.

This is the code from the activity:

editText = (EditText) view.findViewById(R.id.editText);
    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override public void onFocusChange(View v, boolean hasFocus) {

            if (!hasFocus) {
                if (Utility.checkInput(editText) == false) {
                    Toast.makeText(getActivity(), "Enter value!",
                            Toast.LENGTH_SHORT).show();
                    // TODO....
                    // Retain focus - do not allow user to move on.
                    // This is where I am lost...

                }
            }
        }
    });

This is the code from the Utility class:

public class Utility {
    public static boolean checkInput(EditText editText) {
        if (editText.getText().length() != 0) {
            return true;
        }
        return false;
    }
    //.../
  1. Where I am stumped is how to retain focus if the check input returns false. I want to prevent the user from moving forward. I am sure there is a simple solution, but I have not found it.

  2. I am also wondering if the xml ime.Options will affect this.
    Thanks.

EDIT

This is my xml:

<EditText
    android:imeOptions="actionDone"
    android:inputType="textPersonName"
    android:maxLength="24"/>

<spinner ../

<EditText
    android:imeOptions="actionDone"
    android:inputType="phone"
    android:maxLength="12"/>

When I use:

if (!hasFocus) {
    if (Utility.checkInput(name) == false) {
        Toast.makeText(AddDriverUserActivity.this, "Enter value!",Toast.LENGTH_SHORT).show(); 
         name.requestFocus();
      }
 }

The problem is, I am using action done (to hide the keyboard), as the user then selects from a spinner then proceeds to the next EditText. So the toast isn't showing until I touch the next edit text (phone) and the focus is then set on two edit texts:

enter image description here

When I reset:

android:imeOptions="actionDone" to actionNext it shows the toast and then proceeds to the next edittext, as shown in the screen shot, both are focused.

Request focus doesn't prevent it from moving from the edittext.


Solution

  • Use View.requestFocus()

    // Retain focus - do not allow user to move on.
    editText.requestFocus();