簡體   English   中英

如何從軟鍵盤獲取輸入文本

[英]How to get input text from soft keyboard

我正在推出這樣的軟鍵盤:

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

inputMethodManager.toggleSoftInputFromWindow(buttonLayout.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);

buttonLayout是我UI上的一個簡單按鈕。
如何提取用戶編寫的內容(不使用EditText字段或隱藏EditText ),以便用戶無法查看或單擊它?

如果沒有EditText,你將會遇到困難。

InputMethod需要連接到視圖。 無論使用哪種視圖,都需要覆蓋onCreateInputConnection以返回一個自定義InputConnection對象,該對象至少實現commitText(用於單詞輸入), deleteSurroundingText (用於刪除)和sendKeyEvent (用於假設您處於啞模式的鍵盤),以及所有的完成功能。 輸入連接是復雜的事情,如果你沒有把它搞定,你會搞砸第三方鍵盤如Swiftkey和Swype。 我真的不建議這樣做。

如果你想這樣做,你最好的機會就是宣稱你的窗口是TYPE_NULL輸入類型。 大多數鍵盤都會自行愚蠢,並假設您只接受該模式下最簡單的命令。 但你不能指望它。

我將查看EditText類返回的InputConnection並盡可能多地復制它。

我也面臨同樣的問題。 如果我隱藏編輯文本, edtTxt.getText().toString()始終為空。 所以我保持喜歡

<EditText
    android:id="@+id/edtTxt"
    android:layout_width="0px"
    android:layout_height="0px" />

這樣用戶就看不到了。 並點擊按鈕

edtTxt.requestFocus();
edtTxt.setText("");
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

inputMethodManager.toggleSoftInputFromWindow(edtTxt.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED,
            0);

現在edtTxt.getText().toString()給出了我用鍵盤輸入的文本。

我會給你一個簡單而簡短的技巧,我已經測試並且工作得非常好


創建EditText0dp高度和0dp寬度,使用戶不會看到EditText甚至它的可見那里。

<EditText
    android:id="@+id/editText"
    android:layout_width="0dp"
    android:layout_height="0dp"
    />

單擊“按鈕”時,請將焦點放在EditText ,然后按照自己的方式打開鍵盤

buttonLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.requestFocus();
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);                inputMethodManager.toggleSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);    
            }
        });

然后在EditText添加一個TextWatcher() ,另外你可以在beforeTextChanged方法中使EditText不可見,它是可選的。 你的TextWatcher看起來像這樣

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
       editText.setVisibility(View.INVISIBLE); //Optional
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {    
    }

    @Override
    public void afterTextChanged(Editable s) {    
       myString = editText.getText().toString(); //Here you will get what you want          
    }
});

暫無
暫無

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

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