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

3

我有一个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);
                }

            }
        });

你还遇到这个问题吗?如果你还需要帮助,请告诉我。 - Shobhit Puri
1个回答

1
假设你的最外层布局是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视图外,如果用户在其他地方点击,它将隐藏键盘。如果您有任何复杂的自定义布局,您可以排除其他视图,如果用户点击它们,它不会隐藏键盘。
对我很有效,希望能帮到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接