2011-07-29 84 views
2

我目前正在開發一個IME,它需要知道文本內容來確定光標所在的行和字符等內容。這適用於全屏模式下的提取文本,但我不想強制全屏。這是我目前執行的相關代碼:Android IME,獲取EditText實例

private ExtractEditText mExtract; 

...

mExtract = new ExtractEditText(this); 
    mExtract.setId(android.R.id.inputExtractEditText); 
    setExtractView(mExtract); 

...

@Override public void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { 
    super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd); 
    String textToMeasure = mExtract.getText().toString().substring(0, newSelStart); 
    Log.w("myIME", "Line: " + countLines(textToMeasure)); 
} 

回答

4

我看了InputMethodService的來源,發現它是如何提取文本爲了使用ExtractEditText,因此我能夠創建一個解決方案:

private String getExtractText() { 
    ExtractedTextRequest req = new ExtractedTextRequest(); 
    req.token = 0; 
    req.flags = InputConnection.GET_TEXT_WITH_STYLES; 
    req.hintMaxLines = 10; 
    req.hintMaxChars = 10000; 
    ExtractedText et = getCurrentInputConnection().getExtractedText(req, InputConnection.GET_EXTRACTED_TEXT_MONITOR); 
    return et.text.toString(); 
} 
+2

如果有人感興趣,請在InputMethodService中使用startExtractingText(boolean inputChanged) – Dan2552

+1

您知道如何獲取在edittext中輸入的行數... – Aniket