Answers:
在XML中,您可以将此行添加到,EditText
View
其中140是最大字符数:
android:maxLength="140"
它为我工作。
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);
}