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:
XML Layout:
In your layout XML file (e.g.,
activity_main.xml
), set theandroid:focusable
andandroid:focusableInTouchMode
attributes totrue
for theEditText
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
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 theEditText
. When the activity starts, theotherView
will gain focus, preventing theEditText
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
Post a Comment