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

编辑文本列表视图

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

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

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


当前回答

我用提交按钮清除所有焦点

XML文件:

<LinearLayout
...
android:id="@+id/linear_layout"
android:focusableInTouchMode="true"> // 1. make this focusableInTouchMode...
</LinearLayout>

JAVA文件:

private LinearLayout mLinearLayout; // 2. parent layout element
private Button mButton;

mLinearLayout = findViewById(R.id.linear_layout);
mButton = findViewById(R.id.button);

mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLinearLayout.requestFocus(); // 3. request focus

            }
        });

我希望这对您有所帮助:)

其他回答

这些解决方案都不适合我。我修复自动对焦的方法是:

<activity android:name=".android.InviteFriendsActivity"
 android:windowSoftInputMode="adjustPan">
    <intent-filter >
    </intent-filter>
</activity>

您可以在布局的第一个TextView中将“focusable”和“focustable in touch mode”设置为true。这样,当活动开始时,TextView将被聚焦,但由于其性质,您将不会在屏幕上看到任何聚焦,当然,也不会显示键盘。。。

做这个,完成你的工作!

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;

感谢纪尧姆。

最简单的方法是在Manifest.xml文件的活动标记中添加android:windowSoftInputMode=“stateAlwaysHidden”