如何阻止 EditText 在 Android 的 Activity 启动时获得焦点

我在 Android 中有一个 Activity,有两个元素:

  1. EditText
  2. ListView

当我的 Activity 启动时,EditText 立即具有输入焦点(闪烁的光标)。 我不希望任何控件在启动时具有输入焦点。 我试过了:

EditText.setSelected(false);
EditText.setFocusable(false);

没有运气。 如何说服 EditTextActivity 启动时不要选择自己?

A simpler solution exists. Set these attributes in your parent layout:

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

findViewById(R.id.mainLayout).requestFocus();

Good comment from Guillaume Perrot:

android:descendantFocusability="beforeDescendants" seems to be the default (integer value is 0). It works just by adding android:focusableInTouchMode="true".

Really, we can see that the beforeDescendants set as default in the ViewGroup.initViewGroup() method (Android 2.2.2). But not equal to 0. ViewGroup.FOCUS_BEFORE_DESCENDANTS = 0x20000;

Thanks to Guillaume.

The problem seems to come from a property that I can only see in the XML form of the layout.

Make sure to remove this line at the end of the declaration within the EditText XML tags:

<requestFocus />

That should give something like that :

<EditText
   android:id="@+id/emailField"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:inputType="textEmailAddress">

//<requestFocus /> /* <– without this line */
</EditText>

</div>