Android set max max limit in bytes

In android, I want editing text with a limit of 255 bytes, so when a user tries to exceed this limit, he will not allow him to write.

All the filters I've seen use character restriction, even in the xml layout.

So, how can I set the filter in edittext to limit to 255 bytes?

+4
source share
2 answers

One solution will be.

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

+3

(char) 2 , : maxlength = "128" editText, ,

                            <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" />
-1

Source: https://habr.com/ru/post/1615400/


All Articles