Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android set edittext max limit in bytes

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?

like image 586
Elior Avatar asked Oct 18 '22 22:10

Elior


1 Answers

One solution would be.

  • Use a TextWatcher on the EditText to get a String of the typed text.
  • Use myString.getBytes().length; to get the size of the string in bytes.
  • 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.

like image 57
J Whitfield Avatar answered Oct 21 '22 17:10

J Whitfield