Android:EditText TextWatcher中的无限循环



我对这段代码有两个问题。感谢上一个问题中的一些好人,我让它正常工作,但现在我再次看到自己处于无限循环中,我不明白它来自哪里。我在这里尝试做的是一个刽子手游戏:处理在 EditText(字面)中读取的单个字符,并在单词 (cuvAles) 中搜索它,然后我想用相应的字母替换下划线。

这是有问题的函数:

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,但它仍然不起作用。这个词与下划线不匹配的原因是我在它们之间有空格以清楚。

2)如果我删除另一个问题(用常量替换字符串),我会得到一个无限循环(我认为这是一个无限循环,因为程序停止响应并且我看到logcat中的GC疯狂工作)。

在更新编辑文本之前删除文本更改侦听器,因为它会继续调用您的文本更改侦听器。

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+" ");
                } 
            }   
        }); 

最新更新