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


当前回答

你必须删除<requestFocus/>

如果你不使用它,还是同样的问题

user LinearLayout作为父类并设置

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

希望对你有所帮助。

其他回答

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

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

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

我也有同样的问题。这简直让我疯了。

我有一个扩展的对话框与一个ScrollView,它有一个表布局与扩展的线性布局,其中包含一个搜索栏和一个编辑文本。

第一个EditText在显示对话框后总是自动对焦,在完成键盘上的文本编辑后,EditText仍然有焦点,键盘仍然可见。

我几乎尝试了这个线程的所有解决方案,没有一个对我有效。

所以这里我的简单解决方案:(text = EditText)

text.setOnEditorActionListener( new OnEditorActionListener( ){
    public boolean onEditorAction( TextView v, int actionId, KeyEvent event ){
        if( (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) ||
            (actionId == EditorInfo.IME_ACTION_DONE) ){
            text.clearFocus( );
            InputMethodManager iMgr = null;
            iMgr = (InputMethodManager)mContext.getSystemService( Context.INPUT_METHOD_SERVICE );
            iMgr.hideSoftInputFromWindow( text.getWindowToken(), 0 );
        }
        return true;
    }
});

顺便说一下,我没有使用以下任何片段来解决它:

//setFocusableInTouchMode( true )
//setFocusable( true )
//setDescendantFocusability( ViewGroup.FOCUS_BEFORE_DESCENDANTS )

而且我没有使用像宽高为1dp的视图这样的间隔项。

希望它能帮助到某人:D

当活动开始时隐藏键盘。在onCreate()中编写以下代码..

InputMethodManager imm = (InputMethodManager)
getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);

清除焦点并从edittext.....中删除光标

editText.clearFocus();

editText.setCursorVisible(false);

删除自动聚焦编辑文本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);

而是以XML的方式。

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

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