我希望能够从EditText删除焦点。例如,如果键盘出现,用户用后退按钮隐藏它,我希望焦点和光标消失。怎样才能做到呢?


当前回答

试着在你的视图上使用这个 这招对我很管用:

<View
    android:id="@+id/fucused"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true"/>

其他回答

您可以使光标和焦点消失

edittext.clearFocus();

但检测时隐藏键盘是一项艰苦的工作。

删除自动聚焦编辑文本android

这对我很有用

在链接中,他们建议使用线性布局,但简单的视图也可以

<View
    android:id="@+id/focus_thief"
    android:layout_width="1dp"
    android:layout_height="1dp"
    android:focusable="true"
    android:focusableInTouchMode="true" />

然后,如果这个“小偷”被放置在布局的顶部(第一个可聚焦的项目),调用clearFocus()将工作。

试着在你的视图上使用这个 这招对我很管用:

<View
    android:id="@+id/fucused"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true"/>

你可以把这个添加到onCreate,它将隐藏键盘每次活动启动。

您还可以通过编程方式将焦点更改为另一个项目。

 this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

你也可以包括android:windowSoftInputMode="stateAlwaysHidden"在你的manifest动作部分。

这相当于:

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

而是以XML的方式。

供参考,你也可以用代码隐藏键盘:

// hide virtual keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mYourEditText.getWindowToken(), 0);