Android EditText字数监听并显示 Android编程实现EditText字数监听并显示的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android EditText字数监听并显示 Android编程实现EditText字数监听并显示的方法

Jacob-wj   2021-03-24 我要评论
想了解Android编程实现EditText字数监听并显示的方法的相关内容吗,Jacob-wj在本文为您仔细讲解Android EditText字数监听并显示的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,EditText,字数监听,显示,下面大家一起来学习吧。

本文实例讲述了Android编程实现EditText字数监听并显示的方法。分享给大家供大家参考,具体如下:

在开发应用的时候,经常会限制用户输入的字数,比如发表评论或者其它什么的,下面来个简单的demo

EditText et_content;//定义一个文本输入框
TextView tv_num;// 用来显示剩余字数
int num = 10;//限制的最大字数

et_content = (EditText) findViewById(R.id.et_content);
tv_num = (TextView) findViewById(R.id.tv_num);
tv_num.setText("10");

下面为EditText文本框添加监听

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

这样就可以实现了

希望本文所述对大家Android程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们