Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

android - How to hide the onscreen keyboard when a DialogFragment is canceled by the setCanceledOnTouchOutside event

If an edittext is currently focused and the user clicks outside of the DialogFragment; I want the on screen keyboard to disappear. I can get it to work for when the DialogFragment is dismissed this way:

InputMethodManager imm;
public View onCreateView(LayoutInflater inflator, ViewGroup container,
        Bundle savedInstanceState) {
imm = (InputMethodManager)getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
...}

@Override 
public void dismiss(){
    imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
    super.dismiss();
}

However, if I try the same thing for when it is canceled by touching outside of the dialogfragment, it will not work. I am trying to do this by overriding onCancel like so:

@Override
public void onCancel(DialogInterface dialog){
    imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
    super.onCancel(dialog);
}

The function is called when the outside touch event happens, but the keyboard is not removed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was able to solve the same problem by sub-classing the dialog and hiding the keyboard before the cancel code on the dialog was executed.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = new Dialog(getActivity(), getTheme()) {
        @Override public void cancel() {
            if (getActivity() != null && getView() != null) {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
            }
            super.cancel();
        }

    };
    return dialog;
}

I tried many alternate approaches including using the DialogFragment's onCancel and onDimiss listeners to no avail. I believe the issue is that the listeners are called asynchronously while the dismiss/cancel is handled synchronously; so by the time your listener is called to hide the keyboard, the window token no longer exists.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...