繁体   English   中英

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

[英]Dismiss keyboard when EditText loses focus

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

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视图,如果用户点击其他任何地方,它将隐藏键盘。 如果您有任何复杂的自定义布局,则可以排除其他视图,如果用户单击该视图,则不会隐藏键盘。

它对我有用。 希望它能帮到你。

暂无
暂无

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

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