vallllll
vallllll

Reputation: 2761

Android dismiss keyboard "naturally"

In my app I have an edittext to enter url and then the edittext has:

android:imeOptions="actionDone"

so when someone presses the enter button of the keyboard, the app connects and the keyboard is dismissed. However I have also a button which can be clicked instead of using the enter command and in this case I would simulate as if the done button of the soft keyboard was pressed instead of using the tipical methods suggested in other threads to dismiss the keyboard. Here is how I do it:

v.findViewById(R.id.button1)
    .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            edit.dispatchKeyEvent(new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0));

        edit.dispatchKeyEvent(new KeyEvent(0, 0, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0));
        }
    }); 

I have a listener for the action and it catches the event:

public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    Log.e(TAG, "Key event received "+actionId);
    if (actionId == EditorInfo.IME_ACTION_DONE || 
            (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP)  ){
        Log.e(TAG, "Key event received  will connect");
        onConnectToServer(null);
        return true;
    }else if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER) return true;
    return false;
}

but i get errors and it seems the key events are sent 100 times I and the keycode is not recognised as enter button. The reasons I don't want to dismiss the keyboard the other method :

InputMethodManager imm = InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mFilterEditText.getWindowToken(), 0);

is because after that code the keyboard doesn't show automatically again when I need it to show in another fragment (+ I have only one activity and many fragments so cannot set in manifest) Any ideas? thks

Upvotes: 2

Views: 1560

Answers (1)

vallllll
vallllll

Reputation: 2761

Can't believe it was so easy:

edi3.onEditorAction(EditorInfo.IME_ACTION_DONE);

Upvotes: 3

Related Questions