如何设置Android EditText输入的最大字符数?我看到setMaxLines,setMaxEMS,但没有任何字符数。
在XML中,您可以将此行添加到EditText
View
,其中140是最大字符数:
android:maxLength="140"
动态:
editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_NUM) });
Zia Xml:
<EditText
android:maxLength="@integer/max_edittext_length"
你可以使用InputFilter,就是这样:
EditText myEditText = (EditText) findViewById(R.id.editText1);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(10); //Filter to 10 characters
myEditText .setFilters(filters);
我总是像这样设置最大值:
<EditText
android:id="@+id/edit_blaze_it
android:layout_width="0dp"
android:layout_height="@dimen/too_high"
<!-- This is the line you need to write to set the max-->
android:maxLength="420"
/>
它对我有用。
etMsgDescription.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maximum_character)});
etMsgDescription.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
tvCharacterLimite.setText(" "+String.valueOf(maximum_character - etMsgDescription.getText().length()));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
这对我有用,这是我发现的最好的。它的最大长度为200个字符
editObservations.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (editObservations.getText().length() >= 201){
String str = editObservations.getText().toString().substring(0, 200);
editObservations.setText(str);
editObservations.setSelection(str.length());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
<EditText
android:id="@+id/edtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter device name"
android:maxLength="10"
android:inputType="textFilter"
android:singleLine="true"/>
InputType必须设置“textFilter”
android:inputType="textFilter"
在任何地方使用此功能:
public static void setEditTextMaxLength(EditText editText, int length) {
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(length);
editText.setFilters(FilterArray);
}