3152

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?

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Mark
  • 39,551
  • 15
  • 41
  • 47

54 Answers54

2838

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"/>
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Morgan Christiansson
  • 29,280
  • 1
  • 19
  • 13
1739

Is the actual problem that you just don't want it to have focus at all? Or you don't want it to show the virtual keyboard as a result of focusing on the EditText? I don't really see an issue with the EditText having a focus on the start, but it's definitely a problem to have the softInput window open when the user did not explicitly request to focus on the EditText (and open the keyboard as a result).

If it's the problem of the virtual keyboard, see the AndroidManifest.xml <activity> element documentation.

android:windowSoftInputMode="stateHidden" - always hide it when entering the activity.

or android:windowSoftInputMode="stateUnchanged" - don't change it (e.g. don't show it if it isn't already shown, but if it was open when entering the activity, leave it open).

Rahul
  • 3,293
  • 2
  • 31
  • 43
Joe
  • 42,036
  • 13
  • 45
  • 61
  • 27
    yet still the cursor is in the first EditText in the layout - even though the keyboard is not shown – martyglaubitz May 20 '14 at 08:17
  • 45
    @Anderson: Nothing about the answer implied that it would prevent the `EditText` from obtaining focus. It actually clearly states that this is how you prevent the *software keyboard IME* from opening automatically on focus; because it is more likely that the bigger concern is the soft keyboard popping up unexpectedly, **not** the focus itself. If your issue is with the `EditText` actually having focus at all, then use someone else's answer. – Joe Jul 08 '14 at 23:38
1202

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

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Silver
  • 12,437
  • 2
  • 14
  • 11
454

The only solution I've found is:

  • Create a LinearLayout (I don't know if other kinds of Layout will work)
  • Set the attributes android:focusable="true" and android:focusableInTouchMode="true"

And the EditText won't get the focus after starting the activity

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Luc
  • 4,549
  • 1
  • 14
  • 3
99

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>
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
floydaddict
  • 1,147
  • 1
  • 7
  • 5
88

using the information provided by other posters, I used the following solution:

in the layout XML

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

<!-- AUTOCOMPLETE -->
<AutoCompleteTextView
    android:id="@+id/autocomplete"
    android:layout_width="200dip"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dip"
    android:inputType="textNoSuggestions|textVisiblePassword"/>

in onCreate()

private AutoCompleteTextView mAutoCompleteTextView;
private LinearLayout mLinearLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout);

    //get references to UI components
    mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
    mLinearLayout = (LinearLayout) findViewById(R.id.linearLayout_focus);
}

and finally, in onResume()

@Override
protected void onResume() {
    super.onResume();

    //do not give the editbox focus automatically when activity starts
    mAutoCompleteTextView.clearFocus();
    mLinearLayout.requestFocus();
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
Someone Somewhere
  • 23,475
  • 11
  • 118
  • 166
  • 2
    This is actually the only answer that worked for me. Adding ```android:focusable="true" android:focusableInTouchMode="true"``` prevents the EditTexts from gaining focus on some devices, but on some devices it still doesn't work. I've been searching for a solution for a long time and this works perfectly. Thanks so much. – DIRTY DAVE Dec 30 '21 at 03:17
  • This works better than other techniques! E.g. having `onResume()` force the text field to defocus mostly works but it breaks the second and later uses of the `adjustPan` feature (pan the window contents to fit the text field with soft keyboard), at least on API 22-23. – Jerry101 Jul 31 '22 at 06:48
84

Try clearFocus() instead of setSelected(false). Every view in Android has both focusability and selectability, and I think that you want to just clear the focus.

Keet Sugathadasa
  • 11,595
  • 6
  • 65
  • 80
Eric Mill
  • 3,455
  • 1
  • 25
  • 26
  • 1
    That sounds promising, but at what point in the Activity lifecycle should it be called? If I call it in onCreate(), the EditText still has focus. Should it be called in onResume() or some other location? Thanks! – Mark Oct 12 '09 at 23:36
  • 9
    I combined the accepted answer with this answer. I called `myEditText.clearFocus(); myDummyLinearLayout.requestFocus();` in the `onResume` of the Activity. This ensured the EditText didn't keep the focus when the phone was rotated. – teedyay Oct 14 '10 at 21:02
83

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.

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
MinceMan
  • 7,483
  • 3
  • 38
  • 40
  • 7
    But this will never gain focus in future, how to just stop focus only for initial(activity start) ?? – Jayesh Mar 08 '13 at 07:46
  • 1
    The onTouchListener is called before other touch actions. So by enabling focusable on touch the standard focus happens on the first touch. The keyboard will come up and everything. – MinceMan Mar 09 '13 at 16:36
  • Nice! This one works (although it seems to take the field out of the focus handling TAB sequence). This can be done all in one place without a layout XML part: `if (Build.VERSION.SDK_INT <= 27) {et.setFocusable(false); et.setOnTouchListener(...);}` – Jerry101 Mar 27 '22 at 23:32
75

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 )

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Lee Yi Hong
  • 1,310
  • 13
  • 17
  • 2
    I had to add edittext.clearFocus() in addition to the above to get it working :) – Nav Sep 09 '14 at 13:12
73

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

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Rishabh Saxena
  • 1,765
  • 15
  • 26
  • 4
    worked perfectly for me. one more thing to note is, dont add these lines to scroll view. It wont work in scroll view. But worked perfectly with linear layout. – Karthic Srinivasan Dec 29 '18 at 14:24
52

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>
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
rallat
  • 1,275
  • 1
  • 10
  • 16
49

Simple solution: In AndroidManifest in Activity tag use

android:windowSoftInputMode="stateAlwaysHidden"
Piyush
  • 18,895
  • 5
  • 32
  • 63
Sergey Sheleg
  • 720
  • 6
  • 6
  • 7
    Strictly speaking, this does not solve the issue. the OP said: "I don't want any control to have input focus at startup." Your solution only hides the keyboard, theres a sublte difference. – katzenhut Sep 04 '14 at 10:04
  • @katzenhut yep, thats my issue with this answer exactly. Focusing on my edittext opens up a PlaceAutoComplete activity, so this answer is incomplete – Zach Jan 15 '17 at 06:48
  • This answer would be complete if the question was: How do I always ensure my activity never shows a keyboard. Which is not. – Martin Marconcini Mar 21 '18 at 00:13
43

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

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Zeus
  • 431
  • 4
  • 2
41

The following worked for me in Manifest. Write,

<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Babar Sanah
  • 533
  • 1
  • 7
  • 13
  • 2
    This doesn't un-focus the text field: it merely hides the keyboard. You'll still get a hint that's pushed out of the field, and any color state selectors will display the "focused=true" state. – A. Rager Nov 01 '16 at 18:05
37

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.

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
jakeneff
  • 503
  • 5
  • 7
32

Add android:windowSoftInputMode="stateAlwaysHidden" in the activity tag of the Manifest.xml file.

Source

Piyush
  • 18,895
  • 5
  • 32
  • 63
prgmrDev
  • 910
  • 1
  • 10
  • 20
  • 1
    This doesn't un-focus the text field: it merely hides the keyboard. You'll still get a hint that's pushed out of the field, and any color state selectors will display the "focused=true" state. – A. Rager Nov 01 '16 at 18:05
28

If you have another view on your activity like a ListView, you can also do:

ListView.requestFocus(); 

in your onResume() to grab focus from the editText.

I know this question has been answered but just providing an alternative solution that worked for me :)

bofredo
  • 2,348
  • 6
  • 32
  • 51
Sid
  • 9,508
  • 5
  • 39
  • 60
27

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();
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Jack Slater
  • 271
  • 3
  • 3
23

Add following in onCreate method:

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Piyush
  • 18,895
  • 5
  • 32
  • 63
Vishal Raj
  • 1,755
  • 2
  • 16
  • 35
  • 2
    This doesn't un-focus the text field: it merely hides the keyboard. You'll still get a hint that's pushed out of the field, and any color state selectors will display the "focused=true" state. – A. Rager Nov 01 '16 at 18:05
20

Write this line in your Parent Layout...

 android:focusableInTouchMode="true"
Vishal Vaishnav
  • 3,346
  • 3
  • 26
  • 57
19

Being that I don't like to pollute the XML with something that is related to functionality, I created this method that "transparently" steals the focus from the first focusable view and then makes sure to remove itself when necessary!

public static View preventInitialFocus(final Activity activity)
{
    final ViewGroup content = (ViewGroup)activity.findViewById(android.R.id.content);
    final View root = content.getChildAt(0);
    if (root == null) return null;
    final View focusDummy = new View(activity);
    final View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View view, boolean b)
        {
            view.setOnFocusChangeListener(null);
            content.removeView(focusDummy);
        }
    };
    focusDummy.setFocusable(true);
    focusDummy.setFocusableInTouchMode(true);
    content.addView(focusDummy, 0, new LinearLayout.LayoutParams(0, 0));
    if (root instanceof ViewGroup)
    {
        final ViewGroup _root = (ViewGroup)root;
        for (int i = 1, children = _root.getChildCount(); i < children; i++)
        {
            final View child = _root.getChildAt(i);
            if (child.isFocusable() || child.isFocusableInTouchMode())
            {
                child.setOnFocusChangeListener(onFocusChangeListener);
                break;
            }
        }
    }
    else if (root.isFocusable() || root.isFocusableInTouchMode())
        root.setOnFocusChangeListener(onFocusChangeListener);

    return focusDummy;
}
Takhion
  • 2,706
  • 24
  • 30
18

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

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Jim
  • 189
  • 1
  • 2
16

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

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
mark
  • 1,697
  • 3
  • 14
  • 13
14

For me, what worked on all devices is this:

    <!-- fake first focusable view, to allow stealing the focus to itself when clearing the focus from others -->

    <View
    android:layout_width="0px"
    android:layout_height="0px"
    android:focusable="true"
    android:focusableInTouchMode="true" />

Just put this as a view before the problematic focused view, and that's it.

android developer
  • 114,585
  • 152
  • 739
  • 1,270
13

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.

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Lumis
  • 21,517
  • 8
  • 63
  • 67
13
<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"/>
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
atul
  • 139
  • 1
  • 2
12

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

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
  • 1
    This doesn't un-focus the text field: it merely hides the keyboard. You'll still get a hint that's pushed out of the field, and any color state selectors will display the "focused=true" state. – A. Rager Nov 01 '16 at 18:07
11

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>
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Tarit Ray
  • 944
  • 12
  • 24
  • 3
    This doesn't un-focus the text field: it merely hides the keyboard. You'll still get a hint that's pushed out of the field, and any color state selectors will display the "focused=true" state. – A. Rager Nov 01 '16 at 18:06
9

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();
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Compaq LE2202x
  • 2,030
  • 9
  • 45
  • 62
9

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);
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Sharath kumar
  • 4,064
  • 1
  • 14
  • 20
8

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>
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Ish
  • 194
  • 1
  • 2
  • 13
8

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.
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
drei01
  • 308
  • 5
  • 15
7
View current = getCurrentFocus();

if (current != null) 
    current.clearFocus();
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
DkPathak
  • 452
  • 1
  • 4
  • 16
7

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"
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Mansuu....
  • 1,206
  • 14
  • 27
6

Make sure to remove the line "<requestFocus />" from the EditText tag in xml.

<EditText
   android:id="@+id/input"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content">

   <requestFocus /> <!-- remove this line --> 
</EditText>
Piyush
  • 18,895
  • 5
  • 32
  • 63
Muhammad Aamir Ali
  • 20,419
  • 10
  • 66
  • 57
5

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

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
hassan mirza
  • 139
  • 2
  • 8
4
/** 
 * set focus to top level window
 * disposes descendant focus 
 * disposes softInput 
 * */
public static void topLevelFocus(Context context){
    if(Activity.class.isAssignableFrom(context.getClass())){
        ViewGroup tlView = (ViewGroup) ((Activity) context).getWindow().getDecorView();
        if(tlView!=null){
            tlView.setFocusable(true);
            tlView.setFocusableInTouchMode(true);
            tlView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        }
    }
}
ceph3us
  • 7,326
  • 3
  • 36
  • 43
4

try

edit.setInputType(InputType.TYPE_NULL);

edit.setEnabled(false);
Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
4

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" />
mmBs
  • 8,421
  • 6
  • 38
  • 46
4

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

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Amir Raza
  • 2,320
  • 1
  • 23
  • 32
3

EditText within a ListView does not work properly. It's better to use TableLayout with automatically generated rows when you are using EditText.

John
  • 15,990
  • 10
  • 70
  • 110
MSIslam
  • 4,587
  • 6
  • 25
  • 28
3

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

Mary's
  • 81
  • 1
  • 3
3
<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"/>
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
2

Disable it in onCreate()

final KeyListener edtTxtMessageKeyListener = edtTxtMessage.getKeyListener();
edtTxtMessage.setCursorVisible(false);
edtTxtMessage.setKeyListener(null);

And finally enable it in onClick() of EditText

edtTxtMessage.setCursorVisible(true);
edtTxtMessage.setKeyListener(edtTxtMessageKeyListener);

But the problem is with we have to click twise to bring OnScreenKeyboard for very first time.

@Workaround

InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

Try this also in onClick() :)

Amit Yadav
  • 32,664
  • 6
  • 42
  • 57
2

I had an issue like this and it was due to my selector. The first state was focus even thogh my view was disabled it took the focus state since it was the first one that matched and used it. you can set the first state to disabled like this:

<selector xmlns:android="http://schemas.android.com/apk/res/android">


<item android:drawable="@drawable/text_field_disabled" android:state_enabled="false"/>
<item android:drawable="@drawable/text_field_focused" android:state_focused="true"/>
<item android:drawable="@drawable/text_field_normal"/>

j2emanue
  • 60,549
  • 65
  • 286
  • 456
2

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>
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Akshay Paliwal
  • 3,718
  • 2
  • 39
  • 43
2

The easiest way is to add android:windowSoftInputMode="stateAlwaysHidden" in the activity tag of the Manifest.xml file

Karthik
  • 1,199
  • 2
  • 14
  • 23
  • 2
    This doesn't un-focus the text field: it merely hides the keyboard. You'll still get a hint that's pushed out of the field, and any color state selectors will display the "focused=true" state. – A. Rager Nov 01 '16 at 18:06
2

Do this and get your job done!

android:focusable="true"
android:focusableInTouchMode="true"
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Tulsi
  • 719
  • 7
  • 15
1

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.

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Rohit Patil
  • 1,615
  • 12
  • 9
1

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

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Bukunmi
  • 2,504
  • 1
  • 18
  • 15
1

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);
    }
}
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
1

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.

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Haris
  • 372
  • 3
  • 16
1

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.

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
-5

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

android:windowSoftInputMode="stateAlwaysHidden"