简体   繁体   English

当EditText失去焦点时,关闭键盘

[英]Dismiss keyboard when EditText loses focus

I have an EditText that I want to control the keyboard. 我有一个EditText,我想控制键盘。 When the EditText has focus the keyboard should appear, then as soon as I click on any other view, I want the keyboard to disappear. 当EditText具有焦点时,键盘应该出现,然后一旦我点击任何其他视图,我希望键盘消失。 I try the following code but it did work 我尝试以下代码但它确实有效

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

            }
        });

Assuming your outermost layout is RelativeLayout (You can do the similar thing for others as well), you can do something like following: 假设您的最外层布局是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);
}

In onTapOutsideBehaviour function here, other that your EditText and Button views, if user clicks anywhere else, it will hide the keyboard. onTapOutsideBehaviour函数中,您的EditTextButton视图,如果用户点击其他任何地方,它将隐藏键盘。 If you have any complex custom layout, you can exclude other views on which if user clicks, it does not hide the keyboard. 如果您有任何复杂的自定义布局,则可以排除其他视图,如果用户单击该视图,则不会隐藏键盘。

It worked for me. 它对我有用。 Hope it helps you. 希望它能帮到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM