一、前言:这个代码也是借鉴别人写的,我也看不太懂。为了方便日后用到就用这篇文章记录一下。
二、代码展示
- /**
- * 禁止EditText输入空格
- *
- * @param editText
- */
-
-
- public static void setEditTextInhibitInputSpace(EditText editText) {
- editText.addTextChangedListener(new TextWatcher() {
- @Override
- public void onTextChanged(CharSequence s, int start, int before,
- int count) {
- if (s.toString().contains(" ")) {
- String[] str = s.toString().split(" ");
- String str1 = "";
- for (int i = 0; i < str.length; i++) {
- str1 += str[i];
- }
- editText.setText(str1);
- editText.setSelection(start);
- }
- }
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count,
- int after) {
- }
- @Override
- public void afterTextChanged(Editable s) {
- }
- });
-
- }
-
- /**
- * 禁止EditText输入特殊字符
- *
- * @param editText
- */
- public static void setEditTextInhibitInputSpeChat(EditText editText) {
-
- InputFilter filter = new InputFilter() {
- @Override
- public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
- String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
- Pattern pattern = Pattern.compile(speChat);
- Matcher matcher = pattern.matcher(source.toString());
- if (matcher.find()) return "";
- else return null;
- }
- };
- editText.setFilters(new InputFilter[]{filter});
- }
-
三、总结:以上代码可以直接复用