EditText的行号和当前行光标位置。

11

我现在正在开发一个安卓应用程序。我创建了一个带有功能的自定义键盘。我使用edittext来显示输入的文本。Edit text可能有n行。现在我的问题是,我的键盘上有一个向上的按钮。如果我点击向上按钮,我需要回到前一行并保持相同的位置。但是我无法找到当前行的edittext行号和光标位置。请朋友们帮帮我。

2个回答

11

要获取当前光标所在行,请尝试以下代码:

public int getCurrentCursorLine(EditText editText)
{    
    int selectionStart = Selection.getSelectionStart(editText.getText());
    Layout layout = editText.getLayout();

    if (selectionStart != -1) {
        return layout.getLineForOffset(selectionStart);
    }

    return -1;
}

并且对于光标位置使用 getSelectionStart():

int cursorPosition = myEditText.getSelectionStart();

2

如果您没有使用像Courier这样的固定宽度字体,那么这并不容易。

没有函数可以返回原始文本和所需像素宽度的字母位置。您需要自己编写。

您应该像这样测量文本:

paint.setTypeface(Typeface.DEFAULT);// your preference here
paint.setTextSize(33); // have this the same as your text size

String text = "get text here ";

paint.getTextBounds(text, 0, text.length(), bounds);

我会使用一些哈希算法来搜索正确的位置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接