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

CEO goes to heaven, where is Nintendo on earth headed?

Nintendo recently issued a brief obituary: "...

User Growth System Theory

What are we talking about when we talk about user...

Air ticket blind box event operation routine!

As the trend of "everything is a blind box&q...

One out of every two adults has this real "secret"!

Studies have shown that bad breath has become the...

2019 5G Mobile Phone Buying Guide

In the second half of 2019, with the issuance of ...

5 ways for the elderly to use health codes even without smartphones

As the epidemic prevention work deepens, for many...

The most advanced hydrological monitoring "black technology" is all here!

recently The 4th Hydrological Monitoring Instrume...

Browser rendering process and performance optimization

As we all know, the application layer of the Worl...

Flu ≠ cold! Don’t confuse them anymore! You must know these differences →

Although medicine has made great progress in the ...

Community operation management, growth and sustainable core

I think whether a group is well managed or not de...

What? Cockroaches can also make oil? Cooking oil!

What? Cockroaches can also make oil? Cooking oil?...