我終於找到了這個問題的解決方案,它有點醜,但最佳解決問題。問題是,在textchanged之前,文本選擇已經消失,所以我不得不使用處理程序來等待文本被選中時,觀察程序後,像這樣立即設置選項: -
final SpanWatcher watcher = new SpanWatcher() {
@Override
public void onSpanAdded(final Spannable text, final Object what,final int start, final int end) {
final Handler handler = new Handler();//handler to get selection after
certain time
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(noteview.hasSelection()) {
higlightdetect=1;//integer to detect that text was selected
selectionStart = noteview.getSelectionStart();
selectionEnd = noteview.getSelectionEnd();
}else
higlightdetect=0;
}
}, 600);//after 600ms seemed to be the optimal time after selection occurs
}
}
@Override
public void onSpanRemoved(final Spannable text, final Object what,
final int start, final int end) {
// Nothing here.
}
@Override
public void onSpanChanged(final Spannable text, final Object
what,final int ostart, final int oend, final int nstart, final int nend)
{
//The same
final Handler handler = new Handler();//handler to get selection after
certain time
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(noteview.hasSelection()) {
higlightdetect=1;//integer to detect that text was selected
selectionStart = noteview.getSelectionStart();
selectionEnd = noteview.getSelectionEnd();
}else
higlightdetect=0;
}
}, 600);//after 600ms seemed to be the optimal time after selection occurs
}
};
edittext.getText().setSpan(watcher, 0, edittext.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);//set spanwatcher to edittext
當然,當文本被選中不能使用它進行定期打字,因爲它會自動更新文本後立即被我添加的文本守望更改,因此這隻能此代碼: -
@Override
public void beforeTextChanged(CharSequence s, int start, int
count, int after) {
if(higlightdetect==0){//condition to get cursor position without selection
selectionStart = noteview.getSelectionStart();
selectionEnd=selectionStart;
}
public void onTextChanged(CharSequence s, int start, int before, int
count) {
}
@Override
public void afterTextChanged(Editable s) {
Toast.makeText(getthenote.this, String.valueOf(selectionStart),
Toast.LENGTH_SHORT).show();
Toast.makeText(getthenote.this, String.valueOf(selectionEnd),
Toast.LENGTH_SHORT).show();
higlightdetect=0 //resetting higlightdetect
}