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


当前回答

添加到你的父布局,你把你的EditText这个android:focusableInTouchMode="true"

其他回答

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

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

移除焦点但保持可聚焦:

editText.setFocusableInTouchMode(false);
editText.setFocusable(false);
editText.setFocusableInTouchMode(true);
editText.setFocusable(true);

EditText将失去焦点,但可以在新的触摸事件中再次获得焦点。

您可以使光标和焦点消失

edittext.clearFocus();

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

你也可以包括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);