如何在EditText中获取光标位置(x,y)? (Android)

18

如何在Android的EditText中获取光标位置x、y坐标(其中x为行号,y为列号)?


1
在光标中,(x,y)指的是什么?(行号,列号)是吗? - devunwired
是的!我想获取光标的位置(行号,列号)。你能帮助我吗? - hieubk
2个回答

47
int pos = editText.getSelectionStart();
Layout layout = editText.getLayout();
int line = layout.getLineForOffset(pos);
int baseline = layout.getLineBaseline(line);
int ascent = layout.getLineAscent(line);
float x = layout.getPrimaryHorizontal(pos);
float y = baseline + ascent;

你可以在那里获取光标的x和y像素位置。


这对我非常有帮助,因为我正在处理这个问题:https://dev59.com/0F8f5IYBdhLWcg3wFvan - Suragch

4
您可以通过以下方式找到当前选定内容的行号和列号:
// Get the current selection's line number
int line = edittext.getLayout().getLineForOffset(edittext.getSelectionStart());

// Find the index for the start of the selected line. Subtract that from the current selection's index
int column = edittext.getSelectionStart() - edittext.getLayout().getLineStart(line);

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