2012-06-27 45 views
0

我有這段代碼的兩個問題。感謝上一個問題中的一些好人,我讓它正常工作,但現在我再次看到自己處於一個無限循環中,我不知道從哪裏來。我在這裏要做的是一個hang子手遊戲:處理在EditText(litera)中讀取的單個字符,然後用單詞(cuvAles)搜索它,然後我想用相應的字母替換下劃線。Android:無限循環在EditText TextWatcher

下面是這個問題的功能:

litera.addTextChangedListener(new TextWatcher(){ 
      public void afterTextChanged(Editable s) {} 
      public void beforeTextChanged(CharSequence s, int start, int count, int after){} 
      public void onTextChanged(CharSequence s, int start, int before, int count){ 
       String ghici = litera.getText().toString(); 

       if(!ghici.equals("")){ 
       System.out.println(ghici); 
       litera.setText(""); 

       if(cuvAles.contains(ghici)){ 
        int poz = 0; 
        while(cuvAles.indexOf(ghici, poz)!= -1){ 
         poz = cuvAles.indexOf(ghici); 
         String spatii = cuvant.getText().toString(); 
         String spatii2 = spatii.substring(0, poz*2-1) + ghici + spatii.substring(poz*2+1, spatii.length()-2); 
         cuvant.setText(spatii2); 
        } 
       } 
       else gresite.append(ghici+" "); 
       } 
      } 
     }); 

有兩個問題在這裏:

1)String spatii2 = spatii.substring(0, poz*2-1) + ghici + spatii.substring(poz*2+1, spatii.length()-1);拋出一個異常StringIndexOutOfBounds。我認爲這是spatii.length()部分,但我用-2嘗試,但它仍然無效。這個詞與下劃線不匹配的原因是我有他們之間的空間是明確的。我得到一個無限循環(我認爲這是一個無限循環,因爲程序停止響應,我看到logcat中的GC瘋狂地工作) 。更新您的EditText,因爲它會一直在打你的文字變化監聽前

回答

1

刪除文本變化監聽..

litera.addTextChangedListener(new TextWatcher(){ 
      public void afterTextChanged(Editable s) {} 
      public void beforeTextChanged(CharSequence s, int start, int count, int after){} 
      public void onTextChanged(CharSequence s, int start, int before, int count){ 
       String ghici = litera.getText().toString(); 

    litera.removeTextChangedListener(this);    


       if(!ghici.equals("")){ 
       System.out.println(ghici); 
       litera.setText(""); 

       if(cuvAles.contains(ghici)){ 
        int poz = 0; 
        while(cuvAles.indexOf(ghici, poz)!= -1){ 
         poz = cuvAles.indexOf(ghici); 
         String spatii = cuvant.getText().toString(); 
         String spatii2 = spatii.substring(0, poz*2-1) + ghici + spatii.substring(poz*2+1, spatii.length()-2); 
         cuvant.setText(spatii2); 
        } 
       } 
       else gresite.append(ghici+" "); 
       } 
      } 
     }); 
+0

不幸的是不起作用。任何其他想法? 關於字符串索引越界問題? – FloIancu