如何限定edit控件中字符长度

如何限定edit控件中字符长度,第1张

第一中办法是直接限制, Edit1.MaxLength := 4第二种办法自己来实现, 就用你的例子procedure TForm1.Edit1Change(Sender: TObject)

begin

if Length(Edit1.Text) >4 then

ShowMessage('超出范围')

end

一、限制输入个数长度,平时我们会使用下面这两种方法

1、在 xml 文件中设置文本编辑框属性作字符数限制

    如:android:maxLength="10" 即限制最大输入字符个数为10

2、在代码中使用InputFilter 进行过滤

    //editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)})即限定最大输入字符数为20

    也可在InputFilter里添加新方法

一、限制输入字符长度,1个GBK的汉字是2个字符,1个UTF-8的汉字是3个字符,暂时我们都统一处理1个汉字占2个字节来算

上代码:

    etEditText.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) {

                }

                @Override

                public void afterTextChanged(Editable s) {

                    String inputMsg = s.toString().trim()

                    if (!TextUtils.isEmpty(inputMsg)) {

                        String limitMsg = WidgetUtil.getLimitInput(inputMsg, /**rightInfoMaxLen*/20)

                        if (!TextUtils.isEmpty(limitMsg)) {

                            if (!limitMsg.equals(inputMsg)) {

                                etEditText.setText(limitMsg)

                                etEditText.setSelection(limitMsg.length())

                            }

                        }

                    }

               })

 

    /**

     * 限制文本输入

     * @param inputStr

     * @param maxLen

     * @return

     */

    public static String getLimitInput(String inputStr, int maxLen) {

        int origLen = inputStr.length()

        int bytesLen = 0//字节数

        String temp

        for (int i = 0i <origLeni++) {

            temp = inputStr.substring(i, i + 1)

            try {

                if (temp.getBytes(Constants.Encode.UTF_8).length == 3 || temp.getBytes(Constants.Encode.GBK).length == 2) {

                    bytesLen += 2

                } else {

                    bytesLen++

                }

            } catch (UnsupportedEncodingException e) {

                e.printStackTrace()


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/tougao/11172064.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-14
下一篇2023-05-14

发表评论

登录后才能评论

评论列表(0条)

    保存