当前位置: 移动技术网 > IT编程>移动开发>Android > EditText监听方法,实时的判断输入多少字符

EditText监听方法,实时的判断输入多少字符

2019年07月24日  | 移动技术网IT编程  | 我要评论

八度论坛网,倾城之恋演员表,假戏真做悄悄爱上你

最近在写一个小项目,其中有一点用到了显示edittext中输入了多少个字符,像微博中显示剩余多少字符的功能。在edittext提供了一个方法addtextchangedlistener实现对输入文本的监控。下边是我自己写的一个demo。

代码实现:

布局文件main.xml

[html] view plain copy
<?xml version="1.0" encoding="utf-8"?> 
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:orientation="vertical" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 > 
<textview android:id="@+id/tv" 
 android:layout_width="fill_parent" 
 android:layout_height="wrap_content" 
 android:textcolor="@android:color/white" 
 android:text="please input the text:" 
 /> 
<edittext android:id="@+id/et" 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 /> 
</linearlayout> 

activity

[java] view plain copy
package com.damai.test; 
import android.app.activity; 
import android.os.bundle; 
import android.text.editable; 
import android.text.textwatcher; 
import android.widget.edittext; 
import android.widget.textview; 
import android.widget.toast; 
public class testactivity extends activity { 
 private textview mtextview; 
 private edittext medittext; 
 @override 
 public void oncreate(bundle savedinstancestate) { 
  super.oncreate(savedinstancestate); 
  setcontentview(r.layout.main); 
  mtextview = (textview)findviewbyid(r.id.tv); 
  medittext = (edittext)findviewbyid(r.id.et); 
  medittext.addtextchangedlistener(mtextwatcher); 
 } 
 textwatcher mtextwatcher = new textwatcher() { 
  private charsequence temp; 
  private int editstart ; 
  private int editend ; 
  @override 
  public void ontextchanged(charsequence s, int start, int before, int count) { 
   // todo auto-generated method stub 
    temp = s; 
  } 
  @override 
  public void beforetextchanged(charsequence s, int start, int count, 
    int after) { 
   // todo auto-generated method stub 
//   mtextview.settext(s);//将输入的内容实时显示 
  } 
  @override 
  public void aftertextchanged(editable s) { 
   // todo auto-generated method stub 
   editstart = medittext.getselectionstart(); 
   editend = medittext.getselectionend(); 
   mtextview.settext("您输入了" + temp.length() + "个字符"); 
   if (temp.length() > 10) { 
    toast.maketext(testactivity.this, 
      "你输入的字数已经超过了限制!", toast.length_short) 
      .show(); 
    s.delete(editstart-1, editend); 
    int tempselection = editstart; 
    medittext.settext(s); 
    medittext.setselection(tempselection); 
   } 
  } 
 }; 
} 

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网