在Android中,我想要一个编辑框限制为255字节,当用户试图超过此限制时,它不会让他继续输入。我看到的所有过滤器都使用字符限制,即使在XML布局中也是如此。那么我该如何设置编辑框的过滤器以将其限制为255字节?
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) {
}
});
您需要将此示例应用于自己的解决方案。
一个字符(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" />