【问题标题】:android textedit delete substring from string on backspaceandroid textedit 从退格上的字符串中删除子字符串
【发布时间】:2015-03-17 20:12:13
【问题描述】:

我有一个包含文本编辑字段的 Android 活动。这个想法是让用户输入一些带有“空格”的文本(最多 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();
    }



}

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

更新

所以在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
        }

    });

【问题讨论】:

    标签: java android string substring textedit


    【解决方案1】:

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

    【讨论】:

    • 谢谢 :) 这让我走上了正确的道路。只是不能让它工作(见更新)
    猜你喜欢
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多