防止用户在任何地方移动光标位置。光标应始终停留在当前EditText某段选中文本位置。除此之外,用户不应该能够在EditText中选择任何内容。你有什么想法如何实现在Android中使用EditText?
public class CustomEditText extends EditText {
private CustomSelectionChangedListener listener;
@Override
public void onSelectionChanged(int start, int end) {
if (start != -1 && end != -1) {
if (listener != null) {
start = end;
// 如果监听不为空,需要自行处理setSelection
listener.onSelectionChanged(start, end);
return;
}
}
super.onSelectionChanged(start, end);
}
public void setListener(CustomSelectionChangedListener listener) {
this.listener = listener;
}
}
重写onSelectionChanged方法,在监听器中通过textView.setSelection控制光标位置。
mEditText.setListener(new CustomSelectionChangedListener() {
@Override
public void onSelectionChanged(int start, int end) {
//选中的文本起始和结束位置,注意 selectedStart 和 selectedEnd大于等于0
int selectedStart = xxx;
int selectedEnd = xxx;
if (selectedEnd < selectedStart) {
selectedEnd = selectedStart;
}
if (start >= selectedStart && end <= selectedEnd) {
start = end;
mEditText.setSelection(start, end);
} else if (start < selectedStart){
mEditText.setSelection(selectedStart);
} else if (end > selectedEnd) {
mEditText.setSelection(selectedEnd);
}
}
});