EditText中过滤掉回车等

时间:2022-11-23 22:33:40

只需要在为EditText添加一个过滤器就够了。

代码如下:

public class MainActivity extends AppCompatActivity {
    private EditText mEditText;

    public static String stringFilter(String str) throws PatternSyntaxException{
        String regEx = "[/\\:*?<>|\"\n\t]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText= (EditText) findViewById(R.id.id_et);

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

            }
        });

        mEditText.addTextChangedListener(new TextWatcher() {
            private int cou = 0;
            int selectionEnd = 0;
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                cou = before + count;
                String editable = mEditText.getText().toString();
                String str = stringFilter(editable); //过滤特殊字符
                if (!editable.equals(str)) {
                    mEditText.setText(str);
                }
                mEditText.setSelection(mEditText.length());
                cou = mEditText.length();
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }
}