Recently I was writing a small project, one of which used the function of displaying the number of characters entered in edittext, such as the number of characters remaining in Weibo. The addtextchangedlistener method is provided in edittext to monitor the input text. Below is a demo I wrote myself.
Code implementation:
Layout file main. xml
[HTML]View plaincopy
- <? 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 plaincopy
- 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); // display the input content in real time
- }
- @ Override
- Public void aftertextchanged (editable s ){
- // Todo auto-generated method stub
- Editstart = medittext. getselectionstart ();
- Editend = medittext. getselectionend ();
- Mtextview. settext ("You entered" + temp. Length () + "characters ");
- If (temp. Length ()> 10 ){
- Toast. maketext (testactivity. This,
- "The number of words you entered exceeds the limit! ", Toast. length_short)
- . Show ();
- S. Delete (editStart-1, editend );
- Int tempselection = editstart;
- Medittext. settext (s );
- Medittext. setselection (tempselection );
- }
- }
- };
- }
[Go] edittext listening method, which determines in real time how many characters are input