Prefix currency

Adding a prefix to TextInputEditText

Adding a prefix to TextInputEditText which is always visible is surprisingly hard with TextInputLayout. Handling this in a TextWatcher is a lot of code. However, there is an easier way!

Rohail Ahmad
3 min readOct 22, 2020

--

Using a TextWatcher to add an always visible prefix is fairly complicated, if someone clicks in the middle of your prefix, you have to intercept the text and move it to the end or more the cursor to the end immediately. All of this can result in a LOT of code. You need to disable copy/paste, you need to handle onClick, you need to handle text change, etc.

Select all text

It’s tricky to align the background text and the EditText. The reason for that is that padding is in DIPs and text sizes are in SP. Look at compatibility issues here for more on EditText fragmentation. An easier approach would be to extend TextInputEditText which means create your custom PrefixEditText.

It does support prefix text changing. Also, I haven’t checked right to left displays but that should be simple enough.

The code

I am using tempPrefix because if you set prefix before it gets focus then prefix will be visible for all time. Using onFocusChanged listener you can set prefix and then it will be visible on focus to this view.

The XML

The styleable attribute

Usage

Prefix

I am using the currency instance from NumberFormat in this case.

Yayyy! That’s all. I believe you would be able to tweak according to your needs.

Enjoy and hit clap 👏 a few times... Feel free to follow me on Medium, or Linkedin.

--

--

Rohail Ahmad

Android Engineer with @kivrasweden formerly @Eliq & @Inov8