代码之家  ›  专栏  ›  技术社区  ›  Fcoder

在Android中更改EditText中用户输入的字符

  •  2
  • Fcoder  · 技术社区  · 12 年前

    我想更改编辑文本中用户输入的字符。事实上,当用户键入编辑文本时,我想要的是,如果输入字符是“S”,则用“B”字符替换它。我想实时做这件事。

    3 回复  |  直到 12 年前
        1
  •  7
  •   Simon Dorociak    12 年前

    我想更改编辑文本中用户输入的字符。事实上我想要 当用户键入编辑文本时,如果输入字符为“S”,则替换它 带有“B”字符。我想实时做这件事。

    很可能您需要使用 TextWatcher 它非常适合您的目标,并允许您实时处理EditText的内容。

    例子:

    edittext.addTextChangedListener(new TextWatcher() {
    
        public void onTextChanged(CharSequence s, int start, int before, int count) {           
    
        }
    
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {    
    
        }
    
        public void afterTextChanged(Editable s) {
    
        }
    });
    
        2
  •  2
  •   Christian Schulzendorff    9 年前

    正如Sajmon所解释的,您必须实现一个TextWatcher。你必须注意光标。因为用户可以在现有文本字符串的任何位置输入下一个字符(或剪贴板中的序列)。要处理此问题,您必须更改正确位置的字符(不要替换整个文本):

            damageEditLongText.addTextChangedListener(new TextWatcher() {
    
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
    
            @Override
            public void afterTextChanged(Editable s) {
                // Nothing to replace
                if (s.length() == 0)
                    return;
    
                // Replace 'S' by 'B'
                String text = s.toString();
                if (Pattern.matches(".*S.*", text)) {
                    int pos = text.indexOf("S");
                    s.replace(pos, pos + 1, "B");
                }
            }
        });
    
        3
  •  0
  •   sleeping_dragon    12 年前

    使用

    EditText textField = findViewById(R.id.textField);
    String text = textField.getText().toString();
    

    然后你可以使用

    text.replace('b','s');
    

    然后

    textField.setText(text,TextView.BufferType);
    

    TextView.BufferType可以有3个值,如前所述 here