Edit text maximum length and show length in texview

I have an edit text and a text view, and I want to set the maximum length in my text editor, and it appears in my text view, and every time the user enters characters, it will be less than the number of characters. For example, I set the maximum length of my edit text to 150, and if the user enters 150 characters, he / she cannot enter more.

How to fix this problem?

+4
source share
6 answers

To set the maximum length of an EditText (select one or the other):

  • In your XML file (recommended) use the android:maxLength="150"Ex property :

    <EditText
        android:id="@+id/yourEditTextId"
        ...
        android:maxLength="150" />     
    
  • ( onCreate), :

    EditText et = (EditText)findViewById(R.id.yourEditTextId);
    et.setFilters(new InputFilter[] { 
        new InputFilter.LengthFilter(150) // 150 is max length
    });
    

, EditText:

onCreate ( , onCreate):

final EditText et = (EditText)findViewById(R.id.yourEditTextId);
et.addTextChangedListener(new TextWatcher() {
    @Override
    public void afterTextChanged(Editable s) {
        TextView tv = (TextView)findViewById(R.id.yourTextViewId);
        tv.setText(String.valueOf(150 - et.length()));
    }

    @Override
    public void onTextChanged(CharSequence s, int st, int b, int c) 
    { }
    @Override
    public void beforeTextChanged(CharSequence s, int st, int c, int a) 
    { }
});
+10

: maxLength = "150"

        <EditText
         android:id="@+id/editText10"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:ems="10"
         android:maxLength="150"
          />
+1

editText.setFilters( new InputFilter[] { new InputFilter.LengthFilter(YOUR_LENGTH) } );

xml

maxLength = "LENGTH"

set TextWatcher, String .

+1

xml :

android:maxLength="Length_size" // size that you want
0

android:maxLength:"150" EditText .

addTextChangedListener() EditText

yourEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void afterTextChanged(Editable s) {
        TextView textView = (TextView)findViewById(R.id.yourTextViewId);
        textView.setText(String.valueOf(150 - s.toString().length()));
    }

    @Override
    public void onTextChanged(CharSequence s, int st, int b, int c) 
    { }
    @Override
    public void beforeTextChanged(CharSequence s, int st, int c, int a) 
    { }
}
0

I have seen many good solutions, but I would like to give what I think is a more complete and user-friendly solution, which includes:

1, limit length. 2, If the input is larger, give a callback to call your toast. 3, The cursor may be in the middle or in the tail. 4, the user can enter by inserting a row. 5, Always discard the input stream and keep the source.

here: fooobar.com/questions/15163 / ...

You can use the callback to display the left number that can be entered.

0
source

Source: https://habr.com/ru/post/1526469/


All Articles