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

编辑文本列表视图

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

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

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


当前回答

最迟但最简单的答案,只需将其添加到XML的父布局中即可。

android:focusable="true" 
android:focusableInTouchMode="true"

如果对你有帮助,请投票!快乐编码:)

其他回答

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

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

感谢纪尧姆。

我找到的唯一解决方案是:

创建LinearLayout(我不知道其他类型的Layout是否有效)设置属性android:focusable=“true”和android:focuableInTouchMode=“true“

并且EditText在开始活动后无法获得焦点

View current = getCurrentFocus();

if (current != null) 
    current.clearFocus();

ListView中的EditText无法正常工作。使用EditText时,最好将TableLayout与自动生成的行一起使用。

您可以通过使用请求焦点并使用键盘隐藏代码来指定其他小部件的焦点。