简体   繁体   中英

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.

软键盘输入

I would add an editText an make it invisible and put on the focus on it. To show it explicitly:

editText = (EditText)findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);

and hide it again

InputMethodManager imm = (InputMethodManager)   getSystemService(this.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

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;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM