android textedit 从退格键的字符串中删除子字符串

android textedit delete substring from string on backspace

我有一个包含文本编辑字段的 Android activity。这个想法是让用户输入一些带有 "blanks" 的文本(最多 3 个)。使用以下函数插入空格:

public void insertblank(View view){
    EditText editText = (EditText) findViewById(R.id.editText1);


    int lastIndex = 0;
    int count =0;

    while(lastIndex != -1){

           lastIndex = editText.getText().toString().indexOf("______",lastIndex);

           if( lastIndex != -1){
                 count ++;
                 lastIndex+="______".length();
          }
    }
    if(count <= 2){
        editText.append(" ______ ");
    }else{
        Toast.makeText(getBaseContext(), "Maximum of 3 blanks allowed", Toast.LENGTH_LONG).show();
    }



}

我需要的是,当用户退格或编辑文本时,"blanks" 需要被视为一个字符。因此,一旦在该子字符串中按下退格键,______ 就会被删除。

更新

因此,在 Gabe Sechan's 回答的帮助下,我几乎完成了这项工作。我在 onCreate 和 运行 中添加了 addTextChangedListener 以下代码。这允许替换字符串中的所有下划线,而不仅仅是 currentWord 中的下划线。

txt.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            // TODO Auto-generated method stub

            Spannable textSpan = txt.getText();
            final int selection = txt.getSelectionStart();
            final Pattern pattern = Pattern.compile("\w+");
            final Matcher matcher = pattern.matcher(textSpan);
            int end = 0;

            String currentWord = null;
            while (matcher.find()) {
                start = matcher.start();
                end = matcher.end();
                if (start <= selection && selection <= end) {
                    currentWord = textSpan.subSequence(start, end).toString();

                    if(currentWord.contains("_")){
                        String wholeText = txt.getText().toString();
                        Toast.makeText(getApplicationContext(), currentWord+"", Toast.LENGTH_SHORT).show();
                        wholeText = wholeText.replace(currentWord, "");
                        txt.setText(wholeText);  
                        txt.setSelection(txt.getText().length());

                    }

                }
            }





        }

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

            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {

            // TODO Auto-generated method stub
        }

    });

最好的办法是在字段上放置一个 TextWatcher 并在 afterTextChanged 中查找对空白的更改,并在必要时删除整个空白。