In the layout, edittext is often used in the android layout, and the content entered in edittext is often restricted. We can use textwatcher to observe the content entered in the input box and take notes.
Main layout:
<? 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: ellipsize = "Marquee" Android: focusable = "True" Android: marqueerepeatlimit = "Marquee_forever" Android: focusableintouchmode = "True" Android: scrollhorizontally = "True" Android: Text = "Please input the text:"/> <edittext Android: Id = "@ + ID/ET" Android: layout_width = "Match_parent" Android: layout_height = "Wrap_content" Android: inputtype = "Number"/> </linearlayout>
JavaCode:
Package Com. Android. text; Import Android. App. activity; Import Android. OS. Bundle; Import Android. Text. editable; Import Android. Text. textwatcher; Import Android. util. log; Import Android. widget. edittext; Import Android. widget. textview; Import Android. widget. Toast; Public Class Textwatcherdemo Extends Activity { Private Textview mtextview; Private Edittext medittext; /** Called when the activity is first created. */ @ 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 Beforetextchanged (charsequence s, Int Arg1, Int Arg2, Int Arg3) {temp =S ;}@ override Public Void Ontextchanged (charsequence s, Int Arg1, Int Arg2, Int Arg3) {mtextview. settext (s) ;}@ override Public Void Aftertextchanged (editable s) {editstart = Medittext. getselectionstart (); editend =Medittext. getselectionend (); If (Temp. Length ()> 10 ) {Toast. maketext (textwatcherdemo. 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 );}}};}