How to stop EditText from gaining focus when an activity starts in Android?

Viewed 807473

I have an Activity in Android, with two elements:

  1. EditText
  2. ListView

When my Activity starts, the EditText immediately has the input focus (flashing cursor). I don't want any control to have input focus at startup. I tried:

EditText.setSelected(false);
EditText.setFocusable(false);

No luck. How can I convince the EditText to not select itself when the Activity starts?

54 Answers

The problem seems to come from a property that I can only see in the XML form of the layout.

Make sure to remove this line at the end of the declaration within the EditText XML tags:

<requestFocus />

That should give something like that :

<EditText
   android:id="@+id/emailField"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:inputType="textEmailAddress">

   //<requestFocus /> /* <-- without this line */
</EditText>

Late, but maybe helpful. Create a dummy EditText at the top of your layout then call myDummyEditText.requestFocus() in onCreate()

<EditText android:id="@+id/dummyEditTextFocus" 
android:layout_width="0px"
android:layout_height="0px" />

That seems to behave as I expect. No need to handle configuration changes, etc. I needed this for an Activity with a lengthy TextView (instructions).

I use the following code to stop an EditText from stealing the focus when my button is pressed.

addButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        View focused = internalWrapper.getFocusedChild();
        focused.setVisibility(GONE);
        v.requestFocus();
        addPanel();
        focused.setVisibility(VISIBLE);
    }
});

Basically, hide the edit text and then show it again. This works for me as the EditText is **not** in view so it doesn't matter whether it is showing.

You could try hiding and showing it in succession to see if that helps it lose focus.
View current = getCurrentFocus();

if (current != null) 
    current.clearFocus();

You have Edittext and list. In OnStart/On Create, you should set focus on listview: listview.requestfocus()

try

edit.setInputType(InputType.TYPE_NULL);

edit.setEnabled(false);

It can be achieved by inheriting EditText and overriding onTouchEvent.

class NonFocusableEditText: EditText {

    constructor(context: Context): super(context)
    constructor(context: Context, attrs: AttributeSet?): super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): super(context, attrs, defStyleAttr)

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        return if (isFocusable) super.onTouchEvent(event) else false
    }
}

Then you can use it in the layouts like normal EditText:

<com.yourpackage.NonFocusableEditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"    
        android:hint="@string/your_hint"
        android:imeOptions="actionDone"
        android:inputType="textNoSuggestions" />

Simply add android:focusableInTouchMode="true" in the parent layout of EditText and you will get rid of this awkward behavior.

You can specify focus to some other widget by using request focus and use the keyboard hiding code as well.

If you want to hide the keyboard at the start of the activity. Then mention

android:windowSoftInputMode="stateHidden"

To that activity in the manifest file. Problem gets solved.

Cheers.

I clear all focus with submit button

XML file:

<LinearLayout
...
android:id="@+id/linear_layout"
android:focusableInTouchMode="true"> // 1. make this focusableInTouchMode...
</LinearLayout>

JAVA file:

private LinearLayout mLinearLayout; // 2. parent layout element
private Button mButton;

mLinearLayout = findViewById(R.id.linear_layout);
mButton = findViewById(R.id.button);

mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLinearLayout.requestFocus(); // 3. request focus

            }
        });

I hope this helps you :)

A simple and reliable solution, just override this method :

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View v = getCurrentFocus();

    if (v != null &&
            (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) &&
            v instanceof EditText &&
            !v.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        v.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + v.getLeft() - scrcoords[0];
        float y = ev.getRawY() + v.getTop() - scrcoords[1];

        if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom())
            hideKeyboard(this);
    }
    return super.dispatchTouchEvent(ev);
}

public static void hideKeyboard(Activity activity) {
    if (activity != null && activity.getWindow() != null && activity.getWindow().getDecorView() != null) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
    }
}

Lots of working answers have already been provided but I think we can do a little better by using the below simple method

//set focus to input field
private fun focusHere() {
    findViewById<TextView>(R.id.input).requestFocus()
}

in place of input in R.id.input use any other view id to set focus to that view.

You can set your Editext to have the focus attribute disabled, now this can apply in two ways:

  • You can disable focusable as a general attribute

  • Or you can disable FocusableInTouchMode as an attribute specific to that view in touch mode (touchscreen)

The focusable attribute is true by default if that Editext is at the top of the view stack in that activity, for example, a header, it would be focusable upon activity launch.

To Disable Focusable, you can simply set its boolean value to false.

So that would be:

android:focusable="false"

To Disable it FocusableInTouchMode, you can simply set its boolean value to false. So that would be:

android:focusable="false"

You just locate the Textview you want to apply changes to and add the respective pieces of code to their xml specifications in the XML file.

Alternatively, You can click on the Textview inside the layout editor and locate the sidebar displaying all xml attributes for that Textview, then simply scroll down to where "Focusable" and "FocusableInTouchMode" are declared and check them to be either true or false.

add below line in Manifest file where you have mentioned your activity

android:windowSoftInputMode="stateAlwaysHidden"
Related