Hide keyboard in AlertDialog

Gabrielle picture Gabrielle · Sep 1, 2011 · Viewed 12.6k times · Source

I have an alertdialog with an editext. For this Edittext I make keyboard appear and I want that when user press ok or cancel to hide the keyboard. The strange problem is that when user choose ok, the keyboard is hide, but when choose cancel the keyboard doesn't hide an I'm using the same code for both cases.

Here is my code :

final AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle(data);
        final EditText input = new EditText(this);
        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(25);
        input.setFilters(FilterArray);
        input.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager keyboard = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
                keyboard.showSoftInput(input, 0); 
            }
        },200);



        alert.setView(input);

        alert.setPositiveButton(ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                text = input.getText().toString().trim();
                Canvas c = new Canvas(bitmapResult);
                drawTextImage(bitmapResult);
                saveimage();
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
            }
        });

        alert.setNegativeButton(cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                        saveimage();
                        InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                        im.hideSoftInputFromWindow(input.getWindowToken(), 0);
                    }
                });

        alert.show();

where is my mystake? Can anyone help me?

Answer

Gabrielle picture Gabrielle · Sep 1, 2011

I found the solution :

alert.setNegativeButton(cancel,
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            saveimage();
            InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(input.getWindowToken(), 0);
            dialog.cancel();
        }
    });

I should've put dialog.cancel() after I hide the keyboard.