android中限制EditText最大输入字节数

需求:用户只能在输入框内输入15个字节的字符(15个英文字符或5个中文字符)
了解:一个英文字符在Android中占一个字节,一个中文字符在Android中占3个字节
代码
public class MainActivity extends AppCompatActivity {


    private EditText mEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText = (EditText) findViewById(R.id.etInput);
        mEditText.addTextChangedListener(new MyTextWatcher(this, mEditText, 15));
    }

    private class MyTextWatcher implements TextWatcher {
        private Context context;

        private EditText editText;

        private int len; //允许输入的字节长度(一个中文占3个字节)

        public MyTextWatcher(Context context, EditText editText, int len) {
            this.context = context;
            this.editText = editText;
            this.len = len;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String inputStr = editable.toString().trim();
            byte[] bytes = inputStr.getBytes();
            if (bytes.length > len) {
                Toast.makeText(context, "超过规定字符数", Toast.LENGTH_SHORT).show();
                Log.i("str", inputStr);
                //取前15个字节
                byte[] newBytes = new byte[len];
                for (int i = 0; i < len; i++) {
                    newBytes[i] = bytes[i];
                }
                String newStr = new String(newBytes);
                editText.setText(newStr);
                //将光标定位到最后
                Selection.setSelection(editText.getEditableText(), newStr.length());
            }
        }
    }

}

你可能感兴趣的:(android中限制EditText最大输入字节数)