Android IME,获取EditText实例

时间:2011-07-29 13:06:52

标签: android android-softkeyboard

我目前正在开发一个IME,它需要知道文本内容,以确定光标所在的行和字符。这适用于全屏模式下的Extract文本,但我不想强制执行全屏模式。这是我当前实现的相关代码:

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

1 个答案:

答案 0 :(得分: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();
}