简体   繁体   English

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

[英]change user entered character inside an EditText in Android

I want to change user entered character in a EditText. 我想在EditText中更改用户输入的字符。 in fact i want when user types in Edit text, If input character is "S", replaces it with "B" character. 实际上我想要当用户输入编辑文本时,如果输入字符是“S”,则将其替换为“B”字符。 i want do this realtime. 我想要实时做这件事。

I want to change user entered character in a EditText. 我想在EditText中更改用户输入的字符。 in fact i want when user types in Edit text, If input character is "S", replaces it with "B" character. 实际上我想要当用户输入编辑文本时,如果输入字符是“S”,则将其替换为“B”字符。 i want do this realtime. 我想要实时做这件事。

Most likely you need to use TextWatcher that it pretty designated for your goal and allows you to manipulate with content of EditText in realtime. 很可能你需要使用它为你的目标指定的TextWatcher ,并允许你实时操作EditText的内容。

Example: 例:

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) {

    }
});

Like Sajmon explained, you have to implement a TextWatcher. 像Sajmon解释的那样,你必须实现一个TextWatcher。 You have to take care for the cursor. 你必须小心光标。 Because the user can input the next character (or a sequence from the clipboard) at any position in the existing text string. 因为用户可以在现有文本字符串中的任何位置输入下一个字符(或剪贴板中的序列)。 To handle this, you have to change the character at the right position (don't replace the whole text): 要处理此问题,您必须更改正确位置的字符(不要替换整个文本):

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

use 采用

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

then you can use 然后你可以使用

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

followed by 其次是

textField.setText(text,TextView.BufferType);

TextView.BufferType can have 3 values as stated here TextView.BufferType可以有3个值说明这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM