How to stop EditText from gaining focus when an activity starts in Android?

 

To prevent an EditText from gaining focus when an activity starts in Android, you can use the android:focusable and android:focusableInTouchMode attributes in the XML layout file. Here's an example:

  1. XML Layout:

    In your layout XML file (e.g., activity_main.xml), set the android:focusable and android:focusableInTouchMode attributes to true for the EditText you want to prevent from gaining focus.

    xml
  • <EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:focusable="true" android:focusableInTouchMode="true" android:hint="Enter text here" />

    By setting both android:focusable and android:focusableInTouchMode to true, you ensure that the EditText is focusable but won't automatically gain focus when the activity starts.

  • Java Code:

    In your activity's Java code (e.g., MainActivity.java), you can programmatically request focus on another view, such as a different View element or the parent layout.

    java
    1. import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Request focus on another view to prevent EditText from gaining focus View otherView = findViewById(R.id.otherView); otherView.requestFocus(); } }

      In this example, otherView is a placeholder for the view you want to focus on instead of the EditText. When the activity starts, the otherView will gain focus, preventing the EditText from taking focus automatically.

    Remember to replace activity_main.xml and otherView with your actual layout XML file and the desired view, respectively. By combining the XML attributes and Java code, you can prevent an EditText from gaining focus when the activity starts in Android.

    Comments