Reputation: 3266
In android, I want an edit text with limit of 255 bytes, so when the user will try to exceed this limit, it won't let him to write.
All the filters I saw are using characters limit, even in the xml layout.
So how can I set a filter to the edittext in order to limit to 255 bytes?
Upvotes: 5
Views: 2270
Reputation: 755
One solution would be.
perform an action on the EditText based on a threshold you have set in bytes.
final int threshold = 255;
EditText editText = new EditText(getActivity());
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) {
int i = s.toString().getBytes().length;
if(i < threshold){
//Action needed
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
You will need to apply this example to your own solution.
Upvotes: 4
Reputation: 4549
One Charterer (char) is of 2 bytes, if you set the android:maxlength="128" in your editText, you will get the limit you want
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:lines="1"
android:maxLength="128"
android:singleLine="true"
android:visibility="visible" />
Upvotes: -1