I am developing an Android application in which I would like to set Input filter to allow only 21 characters in the EditText.
The XML code snippet I have used is follows
<EditText
android:id="@+id/screen_name"
android:layout_width="300dp"
android:layout_height="match_parent"
android:background="#00000000"
android:enabled="false"
android:gravity="center"
android:hint="Enter your screen name"
android:maxLength="21"
android:text="Raghunathan KE"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold"
android:inputType="text"
android:isScrollContainer="true"
android:focusable="true"/>
And,In Activity,
InputFilter lengthFilter = new InputFilter.LengthFilter(21) {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (dest.length() > getMax()) {
Toast.makeText(Profile.this, "Screen name should not exceed more than 21 characters", Toast.LENGTH_LONG).show();
}
return super.filter(source, start, end, dest, dstart, dend);
}
@Override
public int getMax() {
return super.getMax();
}
};
screenname.setInputFilters(new InputFilter[]{lengthFilter});
It does not allow to enter more than 21 characters but I am unable to intimate the user that the length must not exceed more than 21 characters because the Toast
message inside filter
callback is not displayed.
I have tried using TextWatcher
but it is not getting invoked after 21st character as I have set the limit to 21 using InputFilter
.
Anyone, Please help me find the solution.
Try this code, also keep the max length of your edittext to 21 in xml