安卓EditText中控制光标上移或下移一行
定义如下函数:
//UpDown 0:光标上移 1:光标下移
public boolean moveUpDown(EditText myTextbox,int UpDown) {
int start = myTextbox.getSelectionStart();
int end = myTextbox.getSelectionEnd();
Layout layout = myTextbox.getLayout();
if (start != end) {
int min = Math.min(start, end);
int max = Math.max(start, end);
if(UpDown==0)
myTextbox.setSelection(min);
else
myTextbox.setSelection(max);
if (min == 0 && max == myTextbox.length()) {
return false;
}
return true;
} else {
int line = layout.getLineForOffset(end);
if(UpDown==0)
{
if (line > 0) {
int move;
if (layout.getParagraphDirection(line) ==
layout.getParagraphDirection(line - 1)) {
float h = layout.getPrimaryHorizontal(end);
move = layout.getOffsetForHorizontal(line - 1, h);
} else {
move = layout.getLineStart(line - 1);
}
myTextbox.setSelection(move);
return true;
}
}
else
{
if (line < layout.getLineCount() - 1) {
int move;
if (layout.getParagraphDirection(line) ==
layout.getParagraphDirection(line + 1)) {
float h = layout.getPrimaryHorizontal(end);
move = layout.getOffsetForHorizontal(line + 1, h);
} else {
move = layout.getLineStart(line + 1);
}
myTextbox.setSelection(move);
return true;
}
}
}
return false;
}
引用:
EditText editText=(EditText) findViewById(R.id.sendText); editText.requestFocus(); moveUpDown(editText, 0);
发表评论