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?
To set the max length of the EditText (pick one or the other):
In your XML file (recommended), use the property android:maxLength="150" Ex:
<EditText
    android:id="@+id/yourEditTextId"
    ...
    android:maxLength="150" />     
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) 
    { }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With