Changing TextInputLayout's Hint value as the user types in it

Detained Developer :

TextInputEditText

Here is my TextInputEditText inside TextInputLayout. The hint you can see is set on TextInputLayout.

The user must write 255 characters otherwise the post is not valid.

I want the digit 255 to decrease as the user types and when reached to 0, the hint should be blank.

Here is my code :

private int charactersLeft = 256; is declared outside onCreate method.

And this code is inside onCreate method :

final TextInputLayout postTextInputBase = findViewById(R.id.post_text_input_base);

final TextInputEditText postTextInput = findViewById(R.id.post_text_input);

postTextInput.addTextChangedListener(new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if (charactersLeft == 0) {
            postTextInputBase.setHint(null);
        } else {
            postTextInputBase.setHint((charactersLeft - 1) + " characters left");
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

I also tried to set charactersLeft to characterLeft -= 1 but, the java won't allow me to do that.

Then, how do I do this ?

Anisuzzaman Babla :

Try this. Works with your existing code.

int charactersLeft = 256;
final TextInputLayout postTextInputBase = findViewById(R.id.post_text_input_base);
final TextInputEditText postTextInput = findViewById(R.id.post_text_input);

postTextInput.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {           
        }

        @Override
        public void afterTextChanged(Editable s) {
           if (s.length() == 0) {
                postTextInputBase.setHint(null);
            }else {
                postTextInputBase.setHint((charactersLeft - s.length()) + " characters left");
            }
        }
    });

and Add android:maxLength="256" to your TextInputEditText

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73815&siteId=1