zoukankan      html  css  js  c++  java
  • Android实现限制EditText输入文字的数量

    一: 声明控件。
             TextView hasnumTV;

            TextView hasnum;// 用来显示剩余字数

            int num = 50;// 限制的最大字数



    二: 基本的方法:

                    hasnumTV = (TextView) findViewById(R.id.tv_num);
                    hasnumTV.setText("限" + num + "" + "字以内");

                    editText.addTextChangedListener(new TextWatcher() {
                            private CharSequence temp;
                            private int selectionStart;
                            private int selectionEnd;

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

                            public void beforeTextChanged(CharSequence s, int start, int count,
                                            int after) {
                                    temp = s;
                            }

                            public void afterTextChanged(Editable s) {
                                    // TODO Auto-generated method stub
                                    int number = num - s.length();
                                    hasnumTV.setText("剩余" + "" + number + "个字");
                                    selectionStart = editText.getSelectionStart();
                                    selectionEnd = editText.getSelectionEnd();
                                    if (temp.length() > num) {
                                            s.delete(selectionStart - 1, selectionEnd);
                                            int tempSelection = selectionEnd;
                                            editText.setText(s);
                                            editText.setSelection(tempSelection);// 设置光标在最后
                                    }
                            }
                    });


    基本的效果是做到了输入的限制文字
  • 相关阅读:
    hdu 2200 Eddy's AC难题(简单数学。。)
    hdu 2201 熊猫阿波的故事(简单概率。。)
    hdu 2571 命运(水DP)
    hdu 2955 Robberies(背包DP)
    GDI+图形图像技术1
    C#笔记2__Char类、String类、StringBuilder类 / 正则表达式 /
    C#笔记1__命名空间 / 常量 / object / is、as、...?... :...
    VS2013快捷键及技巧 / 智能插件
    JAVA笔记15__TCP服务端、客户端程序 / ECHO程序 /
    JAVA笔记14__多线程共享数据(同步)/ 线程死锁 / 生产者与消费者应用案例 / 线程池
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/3984755.html
Copyright © 2011-2022 走看看