Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit text Max length and show the length in the texview

Tags:

android

I have a edit text and a text view and I want to set a Max length in my edit text and it show in my text view and every time a user input a characters it will minus the number of character. For example I set the Max length of my edit text to 150 and if the user input 150 characters he/she cannot input any-more.

How to fix this issue?

like image 910
Jeremiah Me Avatar asked Feb 12 '14 04:02

Jeremiah Me


1 Answers

To set the max length of the EditText (pick one or the other):

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

    <EditText
        android:id="@+id/yourEditTextId"
        ...
        android:maxLength="150" />     
    
  2. Programmatically (in your onCreate method), like so:

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

To keep a counter of the length left in the EditText:

Add this listener in your onCreate method (or anywhere, but it makes sense in 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) 
    { }
});
like image 149
Michael Yaworski Avatar answered Oct 13 '22 20:10

Michael Yaworski