2017-07-17 4 views
1

これは簡単な質問のように思えるかもしれませんが、なぜそれが起こるのかわかりません。ユーザーがテキストを変更する前に編集テキストの選択範囲の開始および終了インデックスを取得したい私のTextWatcherでは、私は以下のなかったよう: - しかしedittextでテキストが変更される前にカーソル開始インデックスを取得する

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


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


      } 

両方たselectionStartを、私は両方が .Iがそれらを挿入しようとした返す言葉「ハロー」を選択selection.For例の終了インデックスを返しますselectionEndに任意のキーボード入力が無駄になる前に選択を取得するためのハンドラで使用します。

答えて

0

最終的に私はこの問題の解決策を見つけましたが、少し醜いですが、問題を最適に解決しました。問題はテキストが選択されていないため、テキストが選択されたときに待機するハンドラを使用しなければならないという問題でした。すぐにそのような後の選択を設定するには、ウォッチャー: - それはテキストの後すぐに自動更新は、私が追加したテキストウォッチャーにそれほど変更されますので、これはテキストが選択されている場合にのみ機能します。もちろん、

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 
} 
関連する問題