I have an EditText
field and the user may only input six digits. When the EditText
is focused, it should hint the user that he can only input six digits.
The idea is to display the remaining digits in gray, like this:
When the user inputs a digit, then it appears like this:
(The red vertical bar represents the cursor.)
The cursor should not be positioned behind its current position in both images; the gray digits should only be visible, and should not be selectable.
So in fact I want to set a placeholder text, but retain a part of the placeholder text whilst the user is typing.
I read about the TextInputLayout
class from the Design Support library, but I don't know how I can achieve abovementioned idea.
How to do this?
I will give you only the idea, so implementation is up to you. Create your TextWatcher, in
onTextChanged()
Count how many digits user wrote and depending on this number create string padded with zeros. After it, make zeros be of different color
Spannable textWithTintedZeros = new SpannableString(paddedString);
textWithTintedZeros.setSpan(new ForegroundColorSpan(yourGrey), firstZeroIndex, length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
editText.setText(textWithTintedZeros);
And at last set selection to be before zeros with
editText.setSelection(indexBeforeFirstZero);
Don't forget also to block changing cursor position. I think can be done with
View.OnKeyListener
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