2017-03-14 11 views
3

edittextで入力した特定の単語の色を変更したいと思います。このコードは単語を1回だけ変更します。別の関数を入力すると、色は変わりません。edittextを入力したときに特定の単語の文字色を変更する

tt.addTextChangedListener(new TextWatcher() { 
      final String FUNCTION = "function"; 
      @Override 
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 

      @Override 
      public void onTextChanged(CharSequence s, int start, int before, int count) {} 

      @Override 
      public void afterTextChanged(Editable s) { 
       int index = s.toString().indexOf(FUNCTION); 
       if (index >= 0) { 
        s.setSpan(
          new ForegroundColorSpan(Color.GREEN), 
          index, 
          index + FUNCTION.length(), 
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
       } 
      } 
     }); 

答えて

4

indexOf常に、あなたの文字列をループする必要があるので、最初に見つかった値のインデックスを与え、すべてのfunction文字列を検索し、その上にスパンを適用し、特定のインデックスの使用からindexOf (String str, int fromIndex)

// a single object to apply on all strings 
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.GREEN);  
String s1 = s.toString(); 
int in=0; // start searching from 0 index 

// keeps on searching unless there is no more function string found 
while ((in = s1.indexOf(FUNCTION,in)) >= 0) { 
    s.setSpan(
     fcs, 
     in, 
     in + FUNCTION.length(), 
     Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
    // update the index for next search with length 
    in += FUNCTION.length(); 
} 
を検索しますあなたは \\bはメートルを避けるために、単語の境界を意味どこ regex \\bを使用する必要が divideから divにマッチするのを避けること

アーチングdivdivide

ForegroundColorSpan fcs = new ForegroundColorSpan(Color.GREEN);  
String s1 = s.toString(); 

Pattern pattern = Pattern.compile("\\b"+FUNCTION+"\\b"); 
Matcher matcher = pattern.matcher(s1); 

// keeps on searching unless there is no more function string found 
while (matcher.find()) { 
    s.setSpan(
      fcs, 
      matcher.start(), 
      matcher.end(), 
      Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
} 
+0

それは私のために働く!どうもありがとうございます。 –

+0

私は幸せなコードを助けることができるとうれしいです –

+0

私はアンドロイドでコードエディタを作っています。これをSyntaxハイライターに使用できますか?またはテキストハイライトに関して私が使用できるツールはありますか? –

関連する問題