Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placeholder hint while typing in EditText in Android

Tags:

android

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:

Hint for remaining digits

When the user inputs a digit, then it appears like this:

Hint for remaining digits

(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?

like image 449
MC Emperor Avatar asked Feb 06 '16 12:02

MC Emperor


1 Answers

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
like image 127
Yaroslav Avatar answered Oct 26 '22 15:10

Yaroslav