49

当我们有一个EditText并且它失去焦点时(对于一个不需要键盘的元素),软键盘应该自动隐藏还是我们应该自己隐藏它?

我将焦点从 a AutoCompleteSearchView(应该表现得像EditText我猜的那样)移动到 a ButtonrequestFocus()返回 true,但键盘没有隐藏。

4

10 回答 10

71

最好的方法是为EditText设置一个OnFocusChangeListener,然后将键盘的代码添加到监听器的OnFocusChange方法中。当 EditText 失去焦点时,Android 将自动关闭键盘。

在您的 OnCreate 方法中是这样的:

EditText editText = (EditText) findViewById(R.id.textbox);
OnFocusChangeListener ofcListener = new MyFocusChangeListener();
editText.setOnFocusChangeListener(ofcListener);

然后添加类:

private class MyFocusChangeListener implements OnFocusChangeListener {

    public void onFocusChange(View v, boolean hasFocus){

        if(v.getId() == R.id.textbox && !hasFocus) {

            InputMethodManager imm =  (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

        }
    }
}
于 2013-03-14T15:23:15.853 回答
9

Android 不会为您隐藏键盘。如果您希望键盘在EditText失去焦点时隐藏,请尝试在该事件上使用如下方法:

private void hideKeypad() {
    EditText edtView = (EditText) findViewById(R.id.e_id);

    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(edtView.getWindowToken(), 0);
}
于 2013-03-14T15:11:38.430 回答
7

试试这个

 /**
 * Hide keyboard on touch of UI
 */
public void hideKeyboard(View view) {

    if (view instanceof ViewGroup) {

        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

            View innerView = ((ViewGroup) view).getChildAt(i);

            hideKeyboard(innerView);
        }
    }
    if (!(view instanceof EditText)) {

        view.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard(v);
                return false;
            }

        });
    }

}

/**
 * Hide keyboard while focus is moved
 */
public void hideSoftKeyboard(View view) {
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) contentsContext_
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManager != null) {
            if (android.os.Build.VERSION.SDK_INT < 11) {
                inputManager.hideSoftInputFromWindow(view.getWindowToken(),
                        0);
            } else {
                if (this.getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(this
                            .getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
                view.clearFocus();
            }
            view.clearFocus();
        }
    }
}
于 2014-01-07T06:39:47.223 回答
5

试试这个,也许它会解决你的问题。

private void hideKeyboard() {
    InputMethodManager mImMan = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    mImMan.hideSoftInputFromWindow(mYourEdttxtName.getWindowToken(), 0);
}

您可以从这里找到更多信息。

于 2013-03-14T15:22:15.683 回答
4

您可以覆盖该dispatchTouchEvent方法来实现它:

@Override
public boolean dispatchTouchEvent(MotionEvent event) {

    if (event.getAction() == MotionEvent.ACTION_DOWN) {

        /**
         * It gets into the above IF-BLOCK if anywhere the screen is touched.
         */

        View v = getCurrentFocus();
        if ( v instanceof EditText) {


            /**
             * Now, it gets into the above IF-BLOCK if an EditText is already in focus, and you tap somewhere else
             * to take the focus away from that particular EditText. It could have 2 cases after tapping:
             * 1. No EditText has focus
             * 2. Focus is just shifted to the other EditText
             */

            Rect outRect = new Rect();
            v.getGlobalVisibleRect(outRect);
            if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }
    return super.dispatchTouchEvent( event );
}

奖励:在 EditText 获得焦点的情况下,触发事件的顺序是:

  1. onFocusChange()另一个 EditText 被调用(如果另一个 edittext 失去焦点)
  2. ACTION_DOWN叫做
  3. 最后,onFocusChange()该 EditText 的方法将被调用。
于 2016-06-01T09:25:23.760 回答
2

这个问题的解决方案已经在这里找到了。
它在活动上使用 DispatchTouchEvent,并且不会将每个 EditText 挂钩到 FocusChange 或 Touch 事件。
这是更好的解决方案。

我的 Xamarin 实现如下:

public override bool DispatchTouchEvent(MotionEvent ev)
    {
        if (ev.Action == MotionEventActions.Down)
        {
            var text = CurrentFocus as EditText;
            if (text != null)
            {
                var outRect = new Rect();
                text.GetGlobalVisibleRect(outRect);
                if (outRect.Contains((int) ev.RawX, (int) ev.RawY)) return base.DispatchTouchEvent(ev);
                text.ClearFocus();
                HideSoftKeyboard();
            }
        }
        return base.DispatchTouchEvent(ev);
    }

protected void HideSoftKeyboard()
    {
        var inputMethodManager = (InputMethodManager) GetSystemService(InputMethodService);
        inputMethodManager.HideSoftInputFromWindow(CurrentFocus.WindowToken, 0);
    }
于 2016-09-03T21:17:54.467 回答
2

只需创建一个静态方法

public static void touchScreenAndHideKeyboardOnFocus(View view, final Activity activity) {

    if (view instanceof EditText) {
        view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if(activity != null) {
                       InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
                       if (activity.getCurrentFocus() != null) {
                          inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                       }
                    }
                }
            }
        });
    }

    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            View innerView = ((ViewGroup) view).getChildAt(i);
            touchScreenAndHideKeyboardOnFocus(innerView, activity);
        }
    }
}

view 是您的布局的根视图.. 但要小心,如果您的编辑文本中有另一个焦点侦听器..

于 2016-10-26T08:56:52.240 回答
1

这对我有用:

InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
于 2020-03-04T09:38:26.423 回答
1

只是想在一堆答案中添加一个 Kotlin 简化版本:

// onCreateView of the Fragment
myAutocompleteText.apply {
    setAdapter(adapter) // whatever the adapter is
    setOnFocusChangeListener { _, hasFocus ->
        if (hasFocus) requireActivity().closeKeyboard() // if called from an Activity instead of a Fragment, just replace it's reference instead of requireActivity()
    }
}


/**
 * Hides the keyboard if possible.
 */
object KeyboardUtils {
    fun Activity.hideKeyboard() {
        if (currentFocus != null) {
            (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
        }
    }
}
于 2020-12-24T12:00:19.483 回答
0

我的问题用这段代码解决了(在片段中)

LinearLayout linearLayoutApply=(LinearLayout)rootView.findViewById(id.LinearLayoutApply);

    linearLayoutApply.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus)
            {
                hideKeyBoard(v);
            }
        }
    });

隐藏键盘

 public void hideKeyBoard(View v)
{
    InputMethodManager imm=(InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
于 2016-06-28T10:48:30.080 回答