`

Android中EditText输入字数统计和限制

 
阅读更多


在Android开发应用的时候,文本编辑框中最多输入140个字,经常会显示还剩多少字以限制用户输入的字数,

  EditText content;//定义一个文本输入框

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

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

  content = (EditText) findViewById(R.id.et_content);

      hasnumTV = (TextView) findViewById(R.id.tv_num);

      hasnumTV.setText(num+"");

  下面为EditText文本框添加监听

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



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


              }



          public void onTextChanged(CharSequence s, int start, int before, int count) {
                   temp = s;
              }

                                

              public void afterTextChanged(Editable s) {
                  int number = num - s.length();
                  hasnumTV.setText("" + number);
                  selectionStart = content.getSelectionStart();
                  selectionEnd = content.getSelectionEnd();
                  if (temp.length() > num) {
                      s.delete(selectionStart - 1, selectionEnd);
                      int tempSelection = selectionEnd;
                      content.setText(s);
                      content.setSelection(tempSelection);//设置光标在最后
                  }
              }
     });

分享到:
评论

相关推荐

    Android-AndroidEditText多行文本输入字数统计限制数量

    总结来说,要在`Android`中实现`EditText`的多行文本输入字数统计和限制,需要: 1. 设置`EditText`为多行输入(`android:maxLines`)。 2. 添加`TextWatcher`监听文本变化。 3. 在`onTextChanged()`方法中检查并...

    EditText字数检测与限制

    在Android开发中,`EditText` 是一个非常常见的...在实际应用中,还可以根据需求增加更多功能,比如提示剩余字数、支持汉字和英文混合输入的字数统计等。这个功能对于提升用户体验和确保数据格式正确性具有重要意义。

    Android监听输入框输入字的个数

    本文将深入探讨如何在Android中实现对EditText输入字数的监听,并提供相关示例代码。 首先,我们可以利用EditText的`addTextChangedListener`方法来添加一个TextWatcher监听器。TextWatcher接口提供了三个关键的...

    android之文本框提示剩余字数

    1. 首先,在XML布局文件中定义EditText,并添加一个TextView用于显示字数统计信息。例如: ```xml <EditText android:id="@+id/et_content" android:layout_width="match_parent" android:layout_height="wrap_...

    FJEditTextCount-master.zip

    总结来说,`FJEditTextCount-master`是一个方便的Android库,为开发者提供了一个带有字数统计功能的`EditText`组件。它简化了字数限制与显示的工作,提高了开发效率,同时也提升了应用的用户体验。在实际项目中,...

    popwindow中加载Editext动态评论仿今日头条

    同时,也需要监听文字输入的变化,例如可以实时更新字数统计。 4. **动态加载和显示**:根据需求,PopWindow可能需要动态加载和显示。这意味着我们可能需要在运行时根据用户操作创建PopWindow,并在合适的位置显示...

Global site tag (gtag.js) - Google Analytics