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


当前回答

将这两个属性添加到你的父布局(例如:线性布局,相对布局)

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

它会成功的:)

其他回答

删除自动聚焦编辑文本android

这对我很有用

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

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

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

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

这相当于:

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

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

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

你可以通过设置父元素的属性android:descendantFocusability来避免对元素的任何关注。

这里有一个例子:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/search__scroller"
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ScrollView>

在这里,属性android:descendantFocusability设置为“blocksDescendants”是阻止对子元素的关注。

你可以在这里找到更多信息。

在评论中,你问是否可以聚焦另一个视图而不是EditText。是的,它可以。使用.requestFocus()方法用于你想在开始时聚焦的视图(在onCreate()方法中)

同样聚焦其他视图也会减少一些代码。(例如隐藏键盘的代码)