Several practical methods to limit EditText input characters in Android development

Several practical methods to limit EditText input characters in Android development

In Android development, it is often necessary to limit the input characters of EditText. Here are several different implementation methods.

Using InputFilter

Limit the input by implementing the InputFilter interface. For example, limit the input length to 10.

 InputFilter[] filters = new InputFilter[1]; filters[0] = new InputFilter.LengthFilter(10); editText.setFilters(filters);

Regular expression to determine whether the input is Chinese:

 editText.setFilters(new InputFilter[]{ new InputFilter() { @Override public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) { String regex = "^[\u4E00-\u9FA5]+$"; boolean isChinese = Pattern.matches(regex, charSequence.toString()); if (!Character.isLetterOrDigit(charSequence.charAt(i)) || isChinese) { return ""; } return null; } } });

Using TextWatcher

TextWatcher can be used to monitor text changes and enforce restrictions on input, such as checking if the input contains certain characters and removing characters that are not letters or numbers.

 editText.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) { String editable = evPwd.getText().toString(); String regEx = "[^a-zA-Z0-9]"; //只能输入字母或数字Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(editable); String str = m.replaceAll("").trim(); //删掉不是字母或数字的字符if(!editable.equals(str)){ evPwd.setText(str); //设置EditText的字符evPwd.setSelection(str.length()); //因为删除了字符,要重写设置新的光标所在位置} } @Override public void afterTextChanged(Editable s) { } });

Using XML attributes

Use attributes in XML to restrict EditText input characters, such as android:inputType and android:digits.

Please enter only numbers:

 <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" android:digits="0123456789" />

Only 0~9 lowercase a~z can be entered:

 <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" android:digits="0123456789abcdefghijklmnopqrstuvwxyz" />

Customizing EditText

For more complex requirements, you can implement input restrictions by customizing the EditText control.

 public class LimitEditText extends EditText { public LimitEditText(Context context) { super(context); } public LimitEditText(Context context, AttributeSet attrs) { super(context, attrs); } public LimitEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { return new InnerInputConnecttion(super.onCreateInputConnection(outAttrs), false); } class InnerInputConnecttion extends InputConnectionWrapper implements InputConnection { public mInputConnecttion(InputConnection target, boolean mutable) { super(target, mutable); } /** * 对输入的内容进行拦截* * @param text * @param newCursorPosition * @return */ @Override public boolean commitText(CharSequence text, int newCursorPosition) { // 只能输入字母或者数字if (!Character.isLetterOrDigit(charSequence.charAt(i)) || isChinese) { return false; } return super.commitText(text, newCursorPosition); } @Override public boolean sendKeyEvent(KeyEvent event) { return super.sendKeyEvent(event); } @Override public boolean setSelection(int start, int end) { return super.setSelection(start, end); } } }

Precautions

  • When using TextWatcher, be careful not to create infinite loops. For example, if you modify the text of an EditText directly in the onTextChanged method without proper checks to prevent unnecessary modifications, you may end up with an infinite loop.
  • For complex input restrictions, consider using regular expressions to match and filter text, which can provide more powerful and flexible text processing capabilities.

<<:  How does the Android system automatically synchronize time through the NTP protocol, and the key code logic of the NTP service

>>:  The different concepts of positions in RecyclerView can help you handle data items and user interactions more efficiently.

Recommend

How to carry out SEM delivery in the toB industry?

As a veteran Internet bidder who has worked in th...

Analysis | Why is it becoming increasingly difficult to make Internet products?

Recently, Andrew Chen, head of user growth at Ube...

App promotion: How to do user retention analysis? Make these two points clear!

There are two things you need to clarify before d...

First experience with MIUI V5 on Android 4.4

Last week, MIUI announced that it had officially s...

8 ideas for Baidu promotion plan

In fact, promoting the Internet is not difficult,...

Summary of highlights of Apple's press conference: These things are worth seeing

After watching the press conference with so much ...

This article will help you understand dry eye syndrome

1. What is dry eye syndrome? Dry eye syndrome is ...