限制Android中EditText的文本长度

在Android中限制EditText文本长度的最佳方法是什么?

有没有办法通过XML来做到这一点?

文档

 android:maxLength="10" 

使用inputfilter来限制文本视图的最大长度。

 TextView editEntryView = new TextView(...); InputFilter[] filterArray = new InputFilter[1]; filterArray[0] = new InputFilter.LengthFilter(8); editEntryView.setFilters(filterArray); 
 EditText editText = new EditText(this); int maxLength = 3; editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)}); 

对已经使用自定义inputfilter并且还想限制最大长度的用户的说明:

当您在代码中分配inputfilter时,将清除之前设置的所有inputfilter,包括使用android:maxLength设置的一个filter。 当我尝试使用自定义inputfilter来防止使用我们在密码字段中不允许使用的字符时,我发现了这一点。 使用setFilters设置该filter后,maxLength不再被观察到。 解决scheme是设置maxLength和我的自定义filter一起编程。 像这样的东西:

 myEditText.setFilters(new InputFilter[] { new PasswordCharFilter(), new InputFilter.LengthFilter(20) }); 
 TextView tv = new TextView(this); tv.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(250) }); 

对于其他人想知道如何实现这一点,这里是我的扩展EditTextEditTextNumeric

.setMaxLength(int) – 设置最大数字位数

.setMaxValue(int) – 限制最大整数值

.setMin(int) – 限制最小整数值

.getValue() – 获取整数值

 import android.content.Context; import android.text.InputFilter; import android.text.InputType; import android.widget.EditText; public class EditTextNumeric extends EditText { protected int max_value = Integer.MAX_VALUE; protected int min_value = Integer.MIN_VALUE; // constructor public EditTextNumeric(Context context) { super(context); this.setInputType(InputType.TYPE_CLASS_NUMBER); } // checks whether the limits are set and corrects them if not within limits @Override protected void onTextChanged(CharSequence text, int start, int before, int after) { if (max_value != Integer.MAX_VALUE) { try { if (Integer.parseInt(this.getText().toString()) > max_value) { // change value and keep cursor position int selection = this.getSelectionStart(); this.setText(String.valueOf(max_value)); if (selection >= this.getText().toString().length()) { selection = this.getText().toString().length(); } this.setSelection(selection); } } catch (NumberFormatException exception) { super.onTextChanged(text, start, before, after); } } if (min_value != Integer.MIN_VALUE) { try { if (Integer.parseInt(this.getText().toString()) < min_value) { // change value and keep cursor position int selection = this.getSelectionStart(); this.setText(String.valueOf(min_value)); if (selection >= this.getText().toString().length()) { selection = this.getText().toString().length(); } this.setSelection(selection); } } catch (NumberFormatException exception) { super.onTextChanged(text, start, before, after); } } super.onTextChanged(text, start, before, after); } // set the max number of digits the user can enter public void setMaxLength(int length) { InputFilter[] FilterArray = new InputFilter[1]; FilterArray[0] = new InputFilter.LengthFilter(length); this.setFilters(FilterArray); } // set the maximum integer value the user can enter. // if exeeded, input value will become equal to the set limit public void setMaxValue(int value) { max_value = value; } // set the minimum integer value the user can enter. // if entered value is inferior, input value will become equal to the set limit public void setMinValue(int value) { min_value = value; } // returns integer value or 0 if errorous value public int getValue() { try { return Integer.parseInt(this.getText().toString()); } catch (NumberFormatException exception) { return 0; } } } 

用法示例:

 final EditTextNumeric input = new EditTextNumeric(this); input.setMaxLength(5); input.setMaxValue(total_pages); input.setMinValue(1); 

适用于EditText所有其他方法和属性当然也适用。

由于goto10的观察,我把下面的代码放在一起,以防止丢失其他filter,设置最大长度:

 /** * This sets the maximum length in characters of an EditText view. Since the * max length must be done with a filter, this method gets the current * filters. If there is already a length filter in the view, it will replace * it, otherwise, it will add the max length filter preserving the other * * @param view * @param length */ public static void setMaxLength(EditText view, int length) { InputFilter curFilters[]; InputFilter.LengthFilter lengthFilter; int idx; lengthFilter = new InputFilter.LengthFilter(length); curFilters = view.getFilters(); if (curFilters != null) { for (idx = 0; idx < curFilters.length; idx++) { if (curFilters[idx] instanceof InputFilter.LengthFilter) { curFilters[idx] = lengthFilter; return; } } // since the length filter was not part of the list, but // there are filters, then add the length filter InputFilter newFilters[] = new InputFilter[curFilters.length + 1]; System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length); newFilters[curFilters.length] = lengthFilter; view.setFilters(newFilters); } else { view.setFilters(new InputFilter[] { lengthFilter }); } } 

另一种可以实现的方法是将以下定义添加到XML文件中:

 <EditText android:id="@+id/input" android:layout_width="0dp" android:layout_height="wrap_content" android:inputType="number" android:maxLength="6" android:hint="@string/hint_gov" android:layout_weight="1"/> 

这将限制EditText小部件的最大长度为6个字符。

我有这个问题,我认为我们缺less一个很好解释的方式做这个以编程方式,而不会丢失已经设置的filter。

在XML中设置长度:

正如接受的答案正确地指出,如果你想定义一个固定长度的EditText,你将不会在将来进一步改变,只需在你的EditText XML中定义:

 android:maxLength="10" 

以编程方式设置长度

下面的问题,以编程方式设置长度,你将需要设置一个InputFilter但一旦你设置所有其他filter消失(例如maxLines,inputType等)。 为了避免丢失以前的filter,您需要获取以前应用的filter,添加maxLength,并将filter设置回EditText,如下所示:

 InputFilter[] editFilters = editText.getFilters(); InputFilter[] newFilters = new InputFilter[editFilters.length + 1]; System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length); newFilters[editFilters.length] = new InputFilter.LengthFilter(10); //the desired length editText.setFilters(newFilters); 

这工作正常…

android:maxLength="10"

这将只接受10字符。

这是一个自定义EditText类,允许长度filter与其他filter一起生活。 感谢Tim Gallagher的回答(下)

 import android.content.Context; import android.text.InputFilter; import android.util.AttributeSet; import android.widget.EditText; public class EditTextMultiFiltering extends EditText{ public EditTextMultiFiltering(Context context) { super(context); } public EditTextMultiFiltering(Context context, AttributeSet attrs) { super(context, attrs); } public EditTextMultiFiltering(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setMaxLength(int length) { InputFilter curFilters[]; InputFilter.LengthFilter lengthFilter; int idx; lengthFilter = new InputFilter.LengthFilter(length); curFilters = this.getFilters(); if (curFilters != null) { for (idx = 0; idx < curFilters.length; idx++) { if (curFilters[idx] instanceof InputFilter.LengthFilter) { curFilters[idx] = lengthFilter; return; } } // since the length filter was not part of the list, but // there are filters, then add the length filter InputFilter newFilters[] = new InputFilter[curFilters.length + 1]; System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length); newFilters[curFilters.length] = lengthFilter; this.setFilters(newFilters); } else { this.setFilters(new InputFilter[] { lengthFilter }); } } } 

它在xml中的简单方法:

 android:maxLength="4" 

如果你需要在XML编辑文本中设置4个字符,使用这个

 <EditText android:id="@+id/edtUserCode" android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxLength="4" android:hint="Enter user code" /> 

我看到了很多很好的解决scheme,但是我想给出一个我认为是更完整和用户友好的解决scheme,其中包括:

1,限制长度。
2,如果input更多,给callback触发你的祝酒。
3,光标可以在中间或尾部。
4,用户可以通过粘贴一个string来input。
5,总是丢弃溢出input并保持原点。

 public class LimitTextWatcher implements TextWatcher { public interface IF_callback{ void callback(int left); } public IF_callback if_callback; EditText editText; int maxLength; int cursorPositionLast; String textLast; boolean bypass; public LimitTextWatcher(EditText editText, int maxLength, IF_callback if_callback) { this.editText = editText; this.maxLength = maxLength; this.if_callback = if_callback; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (bypass) { bypass = false; } else { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(s); textLast = stringBuilder.toString(); this.cursorPositionLast = editText.getSelectionStart(); } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.toString().length() > maxLength) { int left = maxLength - s.toString().length(); bypass = true; s.clear(); bypass = true; s.append(textLast); editText.setSelection(this.cursorPositionLast); if (if_callback != null) { if_callback.callback(left); } } } } edit_text.addTextChangedListener(new LimitTextWatcher(edit_text, MAX_LENGTH, new LimitTextWatcher.IF_callback() { @Override public void callback(int left) { if(left <= 0) { Toast.makeText(MainActivity.this, "input is full", Toast.LENGTH_SHORT).show(); } } })); 

我没有做的是,如果用户突出显示当前input的一部分,并尝试粘贴一个很长的string,我不知道如何恢复高光。

例如,最大长度设置为10,用户input“12345678”,并将“345”标记为高亮,并尝试粘贴超过限制的“0000”string。

当我尝试使用edit_text.setSelection(start = 2,end = 4)来恢复原点状态时,结果是,它只是插入2个空格作为'12 345 678',而不是原点高亮。 我希望有人解决这个问题。