Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide keyboard in AlertDialog

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?

like image 415
Gabrielle Avatar asked Sep 01 '11 12:09

Gabrielle


1 Answers

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.

UPDATE IN KOTLIN:

val im: InputMethodManager =
    getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
im.hideSoftInputFromWindow(editText.windowToken, 0)
like image 90
Gabrielle Avatar answered Sep 27 '22 18:09

Gabrielle