Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Stop EditText from Gaining Focus at Activity Startup in Android?

  • Last Updated : 05 Aug, 2021

When working on an Android Project, you might face a hazy error, the activity starts, and then the EditText immediately gets the focus and the soft keyboard is forced open. Well, that’s not something which we expect, and let’s address this, and get rid of it!

Method #1: Removing the request focus, from the EditText

You may force override the focus of the editText and get rid of this issue from the XML itself. Change your editText’s XML block as below:

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!
<EditText
   android:id="@+id/gfgSampleField"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:inputType="number">
   //`<requestFocus />`
   <!--Remove the above tag-->
</EditText>`

Method #2: Removing the Focus Programmatically

Maybe you don’t want to remove the focus from the XML, or you might be using a 3rd party library for text, you may then programmatically change the focus through your java file in the following way:

Java






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

Method #3: Using XML Flags

You may simply remove the focus, using the focusable attribute from the XML, if you are using newer versions of Android Studio simply, like:

<EditText
   android:id="@+id/gfgSampleField"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:inputType="number">
   android:focusable="false"/>

Method #4: Using Dummy EditText

This method is not that efficient as compared to the ones mentioned above, and hence is on a latter number, this includes creating a new dummy editText, that will not be used and will be hidden so that it tricks the OS into not making any field get focus.

<EditText
    android:id="@+id/gfgSampleField"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:inputType="number">
     <requestFocus />
    </EditText>

Method #5: Hardcoding the Android Manifest

This method could be the last resort if you are not able to resolve the issue by any of the possible methods above, this simply instructs the Android Manifest to not enable the Soft keyboard when the activity is launched for the particular issue containing activity. Open the Android.Manifest file and add the below line to the activity which is problematic:

android:windowSoftInputMode="stateAlwaysHidden"

Conclusion

This was every possible way which could be enacted upon to resolve this hazy issue, now you can finally get rid of that pesky focus and continue your project like before.

My Personal Notes arrow_drop_up
Recommended Articles
Page :