Android --- Three ways to limit the number of words (reprinted) in EditView, androideditview
Method 1: Use TextWatcher
Java code
- EditText. addTextChangedListener (new TextWatcher (){
- Private CharSequence temp;
- Private boolean isEdit = true;
- Private int selectionStart;
- Private int selectionEnd;
- @ 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 ){
- }
- @ Override
- Public void afterTextChanged (Editable s ){
- SelectionStart = editText. getSelectionStart ();
- SelectionEnd = editText. getSelectionEnd ();
- Log. I ("gongbiao1", "" + selectionStart );
- If (temp. length ()> Constant. TEXT_MAX ){
- Toast. makeText (KaguHomeActivity. this,
- R. string. edit_content_limit, Toast. LENGTH_SHORT)
- . Show ();
- S. delete (selectionStart-1, selectionEnd );
- Int tempSelection = selectionStart;
- EditText. setText (s );
- EditText. setSelection (tempSelection );
- }
- }
- });
Method 2: Use InputFilter
Java code
- EditText. setFilters (new InputFilter [] {new InputFilter. LengthFilter (100)}); // 100 of the maximum input words
Method 3: Set in XML
Xml Code
- <EditText
- .
- .
- .
- Android: maxLength = "100"
- />
From the MS Platform, some things are really not used to their own
How does one limit the number of words in textview in android?
When developing applications, users are often limited to the number of words they enter, such as posting comments or other things. Below is a simple demo.
EditText et_content; // define a text input box <br> TextView TV _num; // display the remaining words <br> int num = 10; // maximum number of words <br>
Et_content = (EditText) findViewById (R. id. et_content); <br> TV _num = (TextView) findViewById (R. id. TV _num); <br> TV _num.setText ("10"); <br>
Add a listener for the EditText text box below
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 );
... The remaining full text>
How can I limit the number of characters in android EditText?
EditText inherits from TextView and can use TextView attributes.