Edittext行号和当前行光标位置。

时间:2012-03-21 12:32:27

标签: android

现在我正在开发Android应用程序。我创建了一个具有功能的自定义键盘。我正在使用edittext来显示输入的文本。编辑文本可能有n行。现在我的问题是我的键盘上有一个向上按钮。所以,如果我单击向上按钮,那么我必须前一行相同的位置。但我无法找到输出当前行的edittext行号和光标位置。请帮帮我朋友

2 个答案:

答案 0 :(得分:9)

当前光标线的

尝试:

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

答案 1 :(得分:2)

如果你没有使用固定宽度的字体作为courrier,那就不容易了。

没有函数返回源文本的字母位置和所需的宽度(以像素为单位)。你必须写它。

你应该测量文本,如下所示:

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

我会用于搜索正确位置的某些散列算法