簡體   English   中英

Android - 打開軟鍵盤並在沒有對話框或布局或編輯文本的情況下獲取值

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

有沒有辦法只打開軟鍵盤,沒有實際的對話框或輸入字段,並在字符串中獲取輸入值? 鍵盤本身已經有一個“完成”按鈕; 我可以:按下一個按鈕,鍵盤打開它自己的內置輸入框,輸入值,按“完成”,得到一個變量的結果。

軟鍵盤輸入

我會添加一個 editText 使其不可見並將焦點放在它上面。 要明確顯示它:

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

並再次隱藏它

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

我設計了一個不同的解決方案,靈感來自 Tobias 的建議和這個答案 我創建了一個 AlertDialog 彈出窗口,其中包含一個 EditText。 然后我在edittext中添加了一個延遲的“觸摸”以打開軟鍵盤,然后處理“完成”事件以獲取輸入值並關閉底層彈出窗口。 下面是一些示例代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM