2017-07-17 50 views
1

這看起來像一個簡單的問題,但我不明白爲什麼會發生。我想在用戶更改文本之前在我的編輯文本中獲取選擇的開始和結束索引在我TextWatcher我沒有如下: -在edittext中更改文本之前獲取光標起始索引

public void beforeTextChanged(CharSequence s, int start, int count, int after) { 


        selectionStart = edittext.getSelectionStart(); 
        selectionEnd = edittext.getSelectionEnd(); 


      } 

但是兩者selectionStart和選定結束返回selection.For例子的結束索引我選擇一個詞「你好」都返回。我試圖將它們插入在任何鍵盤輸入之前得到選擇的處理程序都無濟於事。

回答

0

我終於找到了這個問題的解決方案,它有點醜,但最佳解決問題。問題是,在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 
}