Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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

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

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 AndroidManifest file and add the below line to the activity which is problematic:

android:windowSoftInputMode="stateAlwaysHidden"

Conclusion

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


Last Updated : 09 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads