一个TexitView的字数监听器

前言

          在很多类似发表状态、说说以及提交意见反馈的地方,都会设置一个字数限制,以防提交时出现什么约定性的错误。但是为了提高用户体验,很多应用就会在输入框的右下角附上一个小小的字数监听器。


效果展示(就类似下面这样的功能)




实现方式

     就是一个简单为TextView加上监听的方法,在进界面  init()里面调用一下就好了。

  

    注:我标的红色的字体是你需要改动的实际代码,其他的都不需要改动,直接复制到代码里放着就行了

         

      help_feedback    //为输入框的控件对象
      tv_num           //输入框右下角字数实时监听展示的textView的控件对象
      200             //最大字数



    
   int num = 200;//限制的最大字数的声明

 

/** * edittext文字个数的显示 */ private void addTextChange() { help_feedback.addTextChangedListener(new TextWatcher() { private CharSequence temp; private int selectionStart; private int selectionEnd; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { temp = s; } @Override public void afterTextChanged(Editable s) { int number = num - s.length(); tv_num.setText(number+"/200"); selectionStart = help_feedback.getSelectionStart(); selectionEnd = help_feedback.getSelectionEnd(); //System.out.println("start="+selectionStart+",end="+selectionEnd); if (temp.length() > num) { s.delete(selectionStart - 1, selectionEnd); int tempSelection = selectionStart; help_feedback.setText(s); help_feedback.setSelection(tempSelection);//设置光标在最后 } } }); }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值