假设用户在 EditText 中输入了一些文本,之后触摸屏幕的其他位置,导致光标位置发生了改变:如何确定新的光标位置?
简单版:
myEditText.getSelectionStart();
如果你想在事件发生时做出反应,你可以尝试:
myEditText.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
// view is myEditText here
}
});
event
允许区分按下和释放之间的差异。
EditText
还有一个 setOnClickListener()
方法,值得一看。
编辑:
我忘了提到 onSelectionChanged(int selStart, int selEnd)
,其中如果位置发生变化,selEnd 等于 selStart。
最好且安全的方法是使用 TextWatcher
。 @Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int cursorIndex = start + 1;
}