我在Android中有一个活动,包含两个元素:

编辑文本列表视图

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

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

没有运气。如何说服EditText在“活动”启动时不选择自己?


当前回答

从EditText in xml文件中删除<requestFocus/>。

<EditText
       android:id="@+id/emailField"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:inputType="textEmailAddress">
    
       //`<requestFocus />` /* <-- remove this tags */
    </EditText>

其他回答

以下内容将阻止EditText在创建时获取焦点,但当您触摸它们时会抓住它。

<EditText
    android:id="@+id/et_bonus_custom"
    android:focusable="false" />

因此,在xml中将focusable设置为false,但关键是在java中,您可以添加以下侦听器:

etBonus.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.setFocusable(true);
        v.setFocusableInTouchMode(true);
        return false;
    }
});

因为您返回的是false,即不使用事件,所以聚焦行为将照常进行。

已经提供了很多有效的答案,但我认为我们可以使用以下简单方法做得更好

//set focus to input field
private fun focusHere() {
    findViewById<TextView>(R.id.input).requestFocus()
}

使用任何其他视图id来设置该视图的焦点,以代替R.id.input中的输入。

存在更简单的解决方案。在父布局中设置这些属性:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true" >

现在,当活动开始时,默认情况下,主布局将聚焦。

此外,我们可以在运行时(例如,在完成子编辑后)通过再次将焦点放在主布局上,从子视图中移除焦点,如下所示:

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

Guillaume Perrot的好评:

android:descendantFocusability=“beforeDescendants”似乎是默认值(整数值为0)。只需添加android:focuableInTouchMode=“true”。

实际上,我们可以看到,在ViewGroup.initViewGroup()方法中,beforeDescendants被设置为默认值(Android 2.2.2)。但不等于0。ViewGroup.FOCUS_BEFORE_DESCENTANS=0x20000;

感谢纪尧姆。

只需在EditText的父布局中添加android:focuableInTouchMode=“true”,您就可以摆脱这种尴尬的行为。

您有编辑文本和列表。在OnStart/On Create中,应该将焦点设置在listview:listview.requestfocus()上