2017-08-13 42 views
0

我想合併多個while循環而不必重複自己。我有一個字符串數組,像這樣:如何在JAVA中合併2個while循環以避免複製

String[] myStrings = { "Home", "Two", "Three" }; 

我的目標是當上述任何字符串數組中EDITTEXT鍵入的應用範圍的影響。我可以重複while循環,而不是使用字符串來開始,但對於乾淨的代碼,我想把所有字符串放在數組中,並將span效果應用於其中的任何一個,如果它在編輯文本中輸入的話。任何想法如何實現這一目標?

public void onTextChanged(CharSequence s, int start, int before, int count) { 
      String str="home"; 
      Spannable spannable =textA.getText(); 
      if(s.length() != 0) { 
       textA.setTextColor(Color.parseColor("#0000FF")); 
       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(str,in)) >= 0) { 
        spannable.setSpan(
          fcs, 
          in, 
          in + str.length(), 
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
        // update the index for next search with length 
        in += str.length(); 
       } 
      } 
     } 

     @Override 
     public void afterTextChanged(Editable s) { 

     } 
    }); 
+0

您的問題的標題似乎與實際問題不匹配....您需要哪一個答案? –

回答

3

您可以嵌套的實際環,搜索,如果它是由外部環路上的一組String小號迭代搜索和裝飾裝修中遇到的特定String

for (String stringToSearch : myStrings){ 
    int in = 0; // start searching from 0 index for each new word to match 
    while ((in = s1.indexOf(stringToSearch,in)) >= 0) { 
    spannable.setSpan(
      fcs, 
      in, 
      in + stringToSearch.length(), 
      Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
    // update the index for next search with length 
    in += stringToSearch.length(); 
    } 
} 
+0

工程,但它是越野車。當您鍵入第一個元素之前鍵入最後一個元素時,跨度不適用 – Simon

+0

hi dave。等待你的回覆,請 – Simon

+1

可能是因爲你必須重新索引'0'爲每個新的'字符串',你想匹配。我更新了更改。試一試。 – davidxxx