If you have an EditText in your activity then I noticed that when the activity is launched the EditText is focused automatically and the keyboard pops up.
This doesn’t seem to be very user friendly. As the keyboard blocks half of the screen and some information is hidden.
Now in this post I would show you how to avoid this scenario.
I have a confession though. The title of this post is a little misleading as I won’t be telling you about how to remove the focus from EditText but rather how to hide the keyboard or prevent it from popping up at the start of the activity.
Why I prefer this rather than removing the focus from the EditText is because it makes sure that the keyboard doesn’t pop up blocking the information on the screen and most importantly the user still sees a blinking cursor in the first EditText in that activity, thereby prompting the user to click on it and fill it.
This seems to be more user-friendly in my opinion. However, for the sake of completeness I would also tell you how to prevent it from even being in focus.
So just add the following line to the <activity> in your Manifest File:
This will stop the keyboard from popping up but the EditText will still be in focus, that is you would see a cursor flashing. However, I fell that in most cases this would be enough.
But if you still want to remove the focus completely, then you need to add the focus to a dummy element as shown below:
<!-- 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"/>
Or as an even simpler approach just add the following line:
to your parent layout.
So that the parent layout looks somewhat like this:
<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: