android - 当 EditText 失去焦点时关闭键盘

标签 android android-layout keyboard

我有一个要控制键盘的 EditText。当 EditText 具有焦点时,键盘应该出现,然后只要我单击任何其他 View ,我希望键盘消失。我尝试了以下代码,但它确实有效

mEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
                } else {
                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
                }

            }
        });

最佳答案

假设您的最外层布局是RelativeLayout(您也可以为其他布局做类似的事情),您可以执行如下操作:

private RelativeLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //....
    layout = (RelativeLayout) findViewById(R.id.yourOutermostLayout);
    onTapOutsideBehaviour(layout);
}   

private void onTapOutsideBehaviour(View view) {
    if(!(view instanceof EditText) || !(view instanceof Button)) {
        view.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard(YourCurrentActivity.this);
                return false;
            }

        });
    }
}


\\Function to hide keyboard
private static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}

在此处的onTapOutsideBehaviour 函数中,除了您的EditTextButton View ,如果用户点击其他任何地方,它将隐藏键盘。如果您有任何复杂的自定义布局,您可以排除其他 View ,如果用户单击这些 View ,它不会隐藏键盘。

它对我有用。希望对你有帮助。

关于android - 当 EditText 失去焦点时关闭键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20979592/

相关文章:

android - 同一 Android 复合组件的多个实例

用于构建 OpenCV 3.2 的 Android.mk 和 Application.mk

android - AsyncTask 停止应用程序

android - 如何使用 1 个 GradientDrawable xml 资源制作 10 个具有 10 个不同边框角半径的 ImageView

android - 按钮填充 TableLayout 中的整行?

wpf - 以编程方式将光标移动到 TextBlock

linux - 系统配置键盘在 Fedora 上不工作

android - 如何在网站输入时禁用移动键盘自动完成

android - 同时查询两个条件的 Realm

android - 当设备改变方向android时改变用户界面