Mark
Mark

Reputation: 39881

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

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?

Upvotes: 3180

Views: 835001

Answers (30)

Silver
Silver

Reputation: 12475

A simpler solution exists. Set these attributes in your parent layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true" >

And now, when the activity starts this main layout will get focus by default.

Also, we can remove focus from child views at runtime (e.g., after finishing child editing) by giving the focus to the main layout again, like this:

findViewById(R.id.mainLayout).requestFocus();

Good comment from Guillaume Perrot:

android:descendantFocusability="beforeDescendants" seems to be the default (integer value is 0). It works just by adding android:focusableInTouchMode="true".

Really, we can see that the beforeDescendants is set as default in the ViewGroup.initViewGroup() method (Android 2.2.2). But not equal to 0. ViewGroup.FOCUS_BEFORE_DESCENDANTS = 0x20000;

Thanks to Guillaume.

Upvotes: 1206

Morgan Christiansson
Morgan Christiansson

Reputation: 29450

Adding the tags android:focusableInTouchMode="true" and android:focusable="true" to the parent layout (e.g. LinearLayout or ConstraintLayout) like in the following example, will fix the problem.

<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
    android:focusable="true" 
    android:focusableInTouchMode="true"
    android:layout_width="0px" 
    android:layout_height="0px"/>

<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
to prevent the dummy from receiving focus again -->
<AutoCompleteTextView android:id="@+id/autotext"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:nextFocusUp="@id/autotext" 
    android:nextFocusLeft="@id/autotext"/>

Upvotes: 2852

Vishal Vaishnav
Vishal Vaishnav

Reputation: 3422

Write this line in your Parent Layout...

 android:focusableInTouchMode="true"

Upvotes: 22

Jim
Jim

Reputation: 189

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).

Upvotes: 18

Jack Slater
Jack Slater

Reputation: 281

Try this before your first editable field:

<TextView  
        android:id="@+id/dummyfocus" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:text="@string/foo"
        />

findViewById(R.id.dummyfocus).setFocusableInTouchMode(true);
findViewById(R.id.dummyfocus).requestFocus();

Upvotes: 28

rallat
rallat

Reputation: 1305

None of these solutions worked for me. The way I fix the autofocus was:

<activity android:name=".android.InviteFriendsActivity"
 android:windowSoftInputMode="adjustPan">
    <intent-filter >
    </intent-filter>
</activity>

Upvotes: 55

jakeneff
jakeneff

Reputation: 523

I needed to clearly focus on all fields programmatically. I just added the following two statements to my main layout definition.

myLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
myLayout.setFocusableInTouchMode(true);

That's it. Fixed my problem instantly. Thanks, Silver, for pointing me in the right direction.

Upvotes: 39

Lumis
Lumis

Reputation: 21639

The simplest thing I did is to set focus on another view in onCreate:

myView.setFocusableInTouchMode(true);
myView.requestFocus();

This stopped the soft keyboard from coming up and there was no cursor flashing in the EditText.

Upvotes: 14

Compaq LE2202x
Compaq LE2202x

Reputation: 2386

At onCreate of your Activity, just add use clearFocus() on your EditText element. For example,

edittext = (EditText) findViewById(R.id.edittext);
edittext.clearFocus();

And if you want to divert the focus to another element, use requestFocus() on that. For example,

button = (Button) findViewById(R.id.button);
button.requestFocus();

Upvotes: 9

mark
mark

Reputation: 1757

Yeah, I did the same thing - create a 'dummy' linear layout which gets the initial focus. Furthermore, I set the 'next' focus IDs so the user can't focus it anymore after scrolling once:

<LinearLayout 'dummy'>
<EditText et>

dummy.setNextFocusDownId(et.getId());
 
dummy.setNextFocusUpId(et.getId());
 
et.setNextFocusUpId(et.getId());

a lot of work just to get rid of focus on a view.

Thanks

Upvotes: 17

Zeus
Zeus

Reputation: 461

You can just set "focusable" and "focusable in touch mode" to value true on the first TextView of the layout. In this way when the activity starts the TextView will be focused but, due to its nature, you will see nothing focused on the screen and, of course, there will be no keyboard displayed...

Upvotes: 46

Akshay Paliwal
Akshay Paliwal

Reputation: 3926

remove<requestFocus /> from your EditText in xml file.

<EditText
       android:id="@+id/emailField"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:inputType="textEmailAddress">
    
       //`<requestFocus />` /* <-- remove this tags */
    </EditText>

Upvotes: 2

user4728480
user4728480

Reputation:

This is the perfect and easiest solution. I always use this in my app.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

Upvotes: 12

MinceMan
MinceMan

Reputation: 7592

The following will stop EditText from taking focus when created but grab it when you touch them.

<EditText
    android:id="@+id/et_bonus_custom"
    android:focusable="false" />

So you set focusable to false in the xml, but the key is in the java, which you add the following listener:

etBonus.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.setFocusable(true);
        v.setFocusableInTouchMode(true);
        return false;
    }
});

Because you are returning false, i.e. not consuming the event, the focusing behavior will proceed like normal.

Upvotes: 86

drei01
drei01

Reputation: 307

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.

Upvotes: 8

Mahmudul Haque Khan
Mahmudul Haque Khan

Reputation: 426

<EditText
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:id="@+id/etComments"
    android:hint="Comments.."
    android:textSize="14dp"
    android:focusable="false"
    android:textStyle="italic"/>

Upvotes: 3

Ish
Ish

Reputation: 304

You can achieve this by creating a dummy EditText with layout width and height set to 0dp, and requesting focus to that view. Add the following code snippet in your xml layout:

<EditText
    android:id="@+id/editText0"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:hint="@string/dummy"
    android:ems="10" 
    >
     <requestFocus />
    </EditText>

Upvotes: 8

Babar Sanah
Babar Sanah

Reputation: 553

The following worked for me in Manifest. Write,

<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>

Upvotes: 43

Tulsi
Tulsi

Reputation: 719

Do this and get your job done!

android:focusable="true"
android:focusableInTouchMode="true"

Upvotes: 2

Mansuu....
Mansuu....

Reputation: 1226

When your activity is opened, the keyboard gets visible automatically which causes the focusing of EditText. You can disable the keyboard by writing the following line in your activity tag in the manifest.xml file.

android:windowSoftInputMode="stateAlwaysHidden|adjustPan"

Upvotes: 8

Tarit Ray
Tarit Ray

Reputation: 994

Write this code inside the Manifest file in the Activity where you do not want to open the keyboard.

android:windowSoftInputMode="stateHidden"

Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.project"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="24" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
         <activity
            android:name=".Splash"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Login"
            **android:windowSoftInputMode="stateHidden"**
            android:label="@string/app_name" >
        </activity>
 
    </application>

</manifest>

Upvotes: 11

DkPathak
DkPathak

Reputation: 452

View current = getCurrentFocus();

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

Upvotes: 7

atul
atul

Reputation: 149

<TextView
    android:id="@+id/textView01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit="marquee_forever"
    android:focusable="true"
    android:focusableInTouchMode="true"
    style="@android:style/Widget.EditText"/>

Upvotes: 14

Sharath kumar
Sharath kumar

Reputation: 4132

The easiest way to hide the keyboard is using setSoftInputMode

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

or you can use InputMethodManager and hide the keyboard like this.

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

Upvotes: 9

floydaddict
floydaddict

Reputation: 1196

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>

Upvotes: 102

hassan mirza
hassan mirza

Reputation: 139

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

Upvotes: 5

Lee Yi Hong
Lee Yi Hong

Reputation: 1340

I had tried several answers individually but the focus is still at the EditText. I only managed to solve it by using two of the below solution together.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/mainLayout"
  android:descendantFocusability="beforeDescendants"
  android:focusableInTouchMode="true" >

( Reference from Silver https://stackoverflow.com/a/8639921/15695 )

and remove

<requestFocus />

at EditText

( Reference from floydaddict https://stackoverflow.com/a/9681809 )

Upvotes: 78

Rohit Patil
Rohit Patil

Reputation: 1625

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.

Upvotes: 1

Rishabh Saxena
Rishabh Saxena

Reputation: 1795

Late but simplest answer, just add this in the parent layout of the XML.

android:focusable="true" 
android:focusableInTouchMode="true"

Upvote if it helped you! Happy Coding :)

Upvotes: 76

Jyotiprakash Das
Jyotiprakash Das

Reputation: 397

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);
    }
}

Upvotes: 1

Related Questions