Android设置EditText的最大字节限制

5
在Android中,我想要一个编辑框限制为255字节,当用户试图超过此限制时,它不会让他继续输入。我看到的所有过滤器都使用字符限制,即使在XML布局中也是如此。那么我该如何设置编辑框的过滤器以将其限制为255字节?

你可以在用户输入时计算它的字节大小,但是在相同编码中不是所有字符都具有相同的字节大小。 - Nanoc
2个回答

4
一种解决方案是。
  • 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) {
    
        }
    });
    

您需要将此示例应用于自己的解决方案。


-1

一个字符(char)占用2个字节,如果你在editText中设置android:maxlength="128",你将得到你想要的限制

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

嗨,我使用string.getBytes().length检查了每个字符,发现在英语中,每个字符由1个字节表示,但希伯来语字符由2个字节表示。因此,如果我将最大长度设置为128,则用户可以输入64个字母,但实际情况并非如此,即使他输入希伯来语,也能输入128个字符。 - Elior

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接