Search code examples
androiduser-inputandroid-softkeyboard

Android - open soft keyboard and get value without dialog or layout or edittext


Is there a way to just open the soft keyboard, without an actual dialog nor an input field, and get the input value in a string? the keyboard itself already has a "done" button; can I just: press a button, keyboard opens with its own builtin inputbox, enter value, press "done", get result in a variable.

soft keyboard input


Solution

  • I designed a different solution, inspired by Tobias suggestions plus this answer. I created an AlertDialog popup with an EditText in it. Then I added a delayed "touch" into the edittext to open the soft keyboard, then handled the "done" event to get the input value and also close the underlying popup. Here is some sample code:

    //Open an AlertDialog popup
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    
    //create a simple EditText
    final EditText input = new EditText(activity);
    input.setInputType(InputType.TYPE_CLASS_NUMBER);
    input.setImeOptions(EditorInfo.IME_ACTION_DONE);
    builder.setView(input);
    
    //touch into the EditText to open the softkeyboard (600ms delay)
    new Handler().postDelayed(new Runnable() {
        public void run() {
            input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
            input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
        }
    }, 600);
    
    
    alertDialog = builder.show();
    AlertDialog finalAlertDialog = alertDialog;
    
    //Handle Keyboard event to get value and close the popup
    input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId <= EditorInfo.IME_ACTION_PREVIOUS)) {
                doOperation();
                finalAlertDialog.cancel();
            }
            return false;
        }
    });