63

In my application I have a single EditText together with some TextViews, button and a spinner. My EditText receives focus since it is the only focusable view in this activity, I believe. My EditText shows with an orange border and cursor on the field.

Now I would like to remove the focus from this field (I don't want the cursor and border to show). Is there a way to do this?

I have been able to focus on the button by doing button.seFocusableInTouchMode() and button.requestFocus(). But this highlights the button and is obviously not what I want.

Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
tobbenb3
  • 657
  • 1
  • 6
  • 9
  • 11
    Not actually a duplicate. That question is asking about preventing the EditText from gaining focus on activity startup. This one is about removing focus. These are different problems. – William Jockusch Jul 12 '14 at 18:19

18 Answers18

52

new to android.. tried

getWindow().getDecorView().clearFocus();

it works for me..

just to add .. your layout should have:

 android:focusable="true"
 android:focusableInTouchMode="true"
Zaraki
  • 3,720
  • 33
  • 39
49

Did you try to use old good View.clearFocus()

SweetWisher ツ
  • 7,296
  • 2
  • 30
  • 74
MishaZ
  • 509
  • 4
  • 2
  • 4
    Doesn't work for me. Calling it in onCreate but the EditText keeps with border and blinking cursor. – User May 04 '12 at 10:38
  • 1
    I used that method and added a OnFocusChangeListener, and focus was cleared and then set (automatically) again. – Ray Britton Sep 04 '12 at 09:03
27

check this question and the selected answer: Stop EditText from gaining focus at Activity startup It's ugly but it works, and as far as I know there's no better solution.

Community
  • 1
  • 1
Maragues
  • 37,861
  • 14
  • 95
  • 96
  • 4
    Thanks, I hadn't seen that one. My EditText was wrapped in a TableLayout, so doing this: solved the problem for me. – tobbenb3 Oct 08 '10 at 13:27
  • great, it really is an ugly problem, and the solution isn't intuitive at all. – Maragues Oct 11 '10 at 08:23
  • 1
    Like so much else in the wonky Android API, and I write this in 2013. – sebrock Jan 08 '13 at 14:06
  • 2018 is here and wants to say that a lot of things got much better in the Android world (Arch Components, etc.), but basic stuff like this, is still a pain… a huge pain. – Martin Marconcini May 18 '18 at 18:40
23

I will try to explain how to remove the focus (flashing cursor) from EditText view with some more details and understanding. Usually this line of code should work

editText.clearFocus()

but it could be situation when the editText still has the focus, and this is happening because clearFocus() method is trying to set the focus back to the first focusable view in the activity/fragment layout.

So if you have only one view in the activity which is focusable, and this usually will be your EditText view, then clearFocus() will set the focus again to that view, and for you it will look that clearFocus() is not working. Remember that EditText views are focusable(true) by default so if you have only one EditText view inside your layout it will aways get the focus on the screen. In this case your solution will be to find the parent view(some layout , ex LinearLayout, Framelayout) inside your layout file and set to it this xml code

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

After that when you execute editText.clearFocus() the parent view inside your layout will accept the focus and your editText will be clear of the focus.

I hope this will help somebody to understand how clearFocus() is working.

Stoycho Andreev
  • 6,163
  • 1
  • 25
  • 27
  • 3
    To me, this API design is a bug on Android. I want to clear the focus, not give it to something else. The API is non-deterministic in practice (even if it sounds it is in theory) and this is horrible. Why on earth would you want your DEFAULT behavior to do something not explicit like “let me find who the first view in your hierarchy is that supports focus and give it to that view… instead of just… you know, removing the focus from your focused view, which is what you’re asking me to do”. The Keyboard Handling / Focus on Android is deplorable. – Martin Marconcini May 18 '18 at 18:42
6

if Edittext parent layout is Linear then add

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

like below

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:focusable="true"
            android:focusableInTouchMode="true">

           <EditText/>
          ............

when Edittext parent layout is Relative then

  android:descendantFocusability="beforeDescendants"
  android:focusableInTouchMode="true"

like

  <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:descendantFocusability="beforeDescendants"
            android:focusableInTouchMode="true">

           <EditText/>
          ............
Omkar
  • 3,040
  • 1
  • 22
  • 42
4

I know is too late, but for somebody whit the same need editText.setFocusable(false) si what you are looking for.

lm2a
  • 835
  • 1
  • 10
  • 19
3

Use the attached code to give the focus to "someone else", this is OK if you have a view where you simply want to dismiss the keyboard and release the focus, you don't really care about who gets it.

Use like this: FocusHelper.releaseFocus(viewToReleaseFocusFrom)

public class FocusHelper {
    public static void releaseFocus(View view) {
        ViewParent parent = view.getParent();
        ViewGroup group = null;
        View child = null;
        while (parent != null) {
            if (parent instanceof ViewGroup) {
                group = (ViewGroup) parent;
                for (int i = 0; i < group.getChildCount(); i++) {
                    child = group.getChildAt(i);
                    if(child != view && child.isFocusable())
                        child.requestFocus();
                }
            }
            parent = parent.getParent();
        }
    }
}

Doc: The method traverses from the child view and up the view tree and looks for the first child to give focus to.

Edit: You can also use the API for this:

View focusableView = v.focusSearch(View.FOCUS_DOWN);
if(focusableView != null) focusableView.requestFocus();
Sveinung Kval Bakken
  • 3,715
  • 1
  • 24
  • 30
2

i had a similar problem with the editText, which gained focus since the activity was started. this problem i fixed easily like this:

you add this piece of code into the layout that contains the editText in xml:

    android:id="@+id/linearlayout" 
    android:focusableInTouchMode="true"

dont forget the android:id, without it i've got an error.

the other problem i had with the editText is that once it gain the first focus, the focus never disappeared. this is a piece of my code in java, it has an editText and a button that captures the text in the editText:

    editText=(EditText) findViewById(R.id.et1);
    tvhome= (TextView)findViewById(R.id.tv_home);
    etBtn= (Button) findViewById(R.id.btn_homeadd);
    etBtn.setOnClickListener(new View.OnClickListener() 
    {   
        @Override
        public void onClick(View v)
        {
            tvhome.setText( editText.getText().toString() );

            //** this code is for hiding the keyboard after pressing the button
            View view = Settings.this.getCurrentFocus();
            if (view != null) 
            {  
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
            //**

            editText.getText().clear();//clears the text
            editText.setFocusable(false);//disables the focus of the editText 
            Log.i("onCreate().Button.onClickListener()", "et.isfocused= "+editText.isFocused());
        }
    });
    editText.setOnClickListener(new View.OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {
            if(v.getId() == R.id.et1)
            {
                v.setFocusableInTouchMode(true);// when the editText is clicked it will gain focus again

                //** this code is for enabling the keyboard at the first click on the editText
                if(v.isFocused())//the code is optional, because at the second click the keyboard shows by itself
                {
                    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
                }
                //**

                Log.i("onCreate().EditText.onClickListener()", "et.isfocused= "+v.isFocused());
            }
            else
                Log.i("onCreate().EditText.onClickListener()", "the listener did'nt consume the event");
        }
    });

hope it will help to some of you!

Lena
  • 71
  • 7
2

For me this worked

Add these attributes to your EditText

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

After this in your code you can simply write

editText.clearFocus()
Joel
  • 353
  • 2
  • 7
1

Just find another view and give it focus instead.

var refresher = FindViewById<MvxSwipeRefreshLayout>(Resource.Id.refresher);

refresher.RequestFocus();
PmanAce
  • 4,000
  • 2
  • 24
  • 29
  • For some reason, this was the best solution for me. I just request focus on linear layout in order to require my edit text to lose their focus –  Apr 30 '17 at 19:37
1

I've tryed much to clear focus of an edit text. clearfocus() and focusable and other things never worked for me. So I came up with the idea of letting a fake edittext gain focus:

<LinearLayout
    ...
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        ...
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <!--here comes your stuff-->

    </LinearLayout>

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/fake"
        android:textSize="1sp"/>

</LinearLayout>

then in your java code:

View view = Activity.this.getCurrentFocus();
                    if (view != null) {
                        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                        fake.requestFocus();
                    }

it will hide the keyboard and remove the focus of any edittext that has it. and also as you see the fake edittext is out of screen and can't be seen

navid
  • 1,022
  • 9
  • 20
  • Logged in just to upvote the answer as no other answer worked. This is a feasible workaround. – T.M Sep 20 '18 at 10:05
0

Just include this line

android:selectAllOnFocus="false"

in the XML segment corresponding to the EditText layout.

harshvardhan
  • 765
  • 13
  • 32
0

If I understand your question correctly, this should help you:

TextView tv1 = (TextView) findViewById(R.id.tv1);
tv1 .setFocusable(false);
Ormoz
  • 2,975
  • 10
  • 35
  • 50
kPieczonka
  • 394
  • 1
  • 14
0

You just have to clear the focus from the view as

EditText.clearFocus()
Mayank Bhatnagar
  • 2,120
  • 1
  • 12
  • 20
0

Since I was in a widget and not in an activity I did:

getRootView().clearFocus();
Boken
  • 4,825
  • 10
  • 32
  • 42
kingston
  • 11,053
  • 14
  • 62
  • 116
0

You only have to set the ViewGroup with the attribute:

android:focusableInTouchMode="true"

The ViewGroup is the layout that includes every child view.

0

Just add this line in your parent layout(e.g., constraint or Linear)

android:focusableInTouchMode="true"
kashinath
  • 1
  • 2
-1
<EditText android:layout_height="wrap_content" android:background="@android:color/transparent" android:layout_width="match_parent" 
    android:clickable="false"
     android:focusable="false"
     android:textSize="40dp"
     android:textAlignment="center" 
    android:textStyle="bold"  
    android:textAppearance="@style/Base.Theme.AppCompat.Light.DarkActionBar" 
   android:text="AVIATORS"/>
vithika
  • 213
  • 1
  • 5
  • 16