A module designed to encapsulate the use of an Android EditText field for gathering currency information from a user. Supports all ISO-3166 compliant locales/currencies.

Overview

CurrencyEditText

CurrencyEditText is an extension of Android's EditText view object. It is a module designed to provide ease-of-use when using an EditText field for gathering currency information from a user.

CurrencyEditText is designed to work with all ISO-3166 compliant locales (which should include all locales Android ships will).

If you find that a certain locale is causing issues, please open an Issue in the Issue Tracker.

Getting Started

Getting started is easy. Just add the library as a dependency in your projects build.gradle file. Be sure you've listed mavenCentral as a repository:

repositories {
    mavenCentral()
}
        
dependencies{
    compile 'com.github.blackcat27:library:2.0.2-SNAPSHOT'
}

Alternatively, if you're having issues with mavenCentral, try JitPack:

repositories{
    maven { url "https://jitpack.io" }
}
        
dependencies {
    compile 'com.github.BlacKCaT27:CurrencyEditText:2.0.2'
}

Note: Users of the latest Android Studio Gradle plugin should migrate their build.gradle files to use 'implementation' instead of 'compile'.

Using The Module

Using the module is not much different from using any other EditText view. Simply define the view in your XML layout:

<com.blackcat.currencyedittext.CurrencyEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

You're done! The CurrencyEditText module handles all the string manipulation and input monitoring required to allow for a clean, easy-to-use currency entry system.

In Action

In its default state, CurrencyEditText view appears as an EditText box with the hint set to the users local currency symbol.

Default State

As a user enters additional values, they will appear starting with the right-most digit, pushing older digit entries left as they type.

Entered Text

Depending on the users Locale and Language settings, the displayed text will automatically be formatted to the users local standard. For example, when the users selects "German", the Euro symbol appears on the right, as seen below.

Entered Text

Hints

By default, CurrencyEditText provides a 'hint' value for the text box. This default value is the Currency Code symbol for the users given Locale setting. This is useful for debugging purposes, as well as provides clean and easy to understand guidance to the user.

If you'd prefer to set your own hint text, simply set the hint the same way you would for any other EditText field. You can do this either in your XML layout or in code. To remove the hint entirely, set the hint to an empty string ("").

Attributes

By default, CurrencyEditText does not allow negative number input. This is due to the fact that by far the most common use-case for currency input involves transaction information, where the absolute value of the transaction is entered separately from declaring a deposit or withdrawl.

However, if you do need to support negative number input, you can enable it by setting the allow_negative_values attribute.

In xml:

<com.blackcat.currencyedittext.CurrencyEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:allow_negative_values="true"
    />

In java:

CurrencyEditText tb = (CurrencyEditText) findViewById(R.id.test);
tb.setAllowNegativeValues(true);

You can also set the decimal digits position (see below) via xml or java

In xml:

<com.blackcat.currencyedittext.CurrencyEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:decimal_digits="0"
    />

In java:

CurrencyEditText tb = (CurrencyEditText) findViewById(R.id.test);
tb.setDecimalDigits(0);

Retrieving and Handling Input

As CurrencyEditText is an extension of the EditText class, it contains all the same getters and setters that EditText provides.

To retrieve the fully formatted String value as shown to the user, simply call your CurrencyEditText objects getText() method.

However, you'll likely need to actually do something useful with the users input. To help developers more easily retrieve this information, CurrencyEditText provides the getRawValue() method. This method provides back the raw numeric values as they were input by the user, and should be treated as if it were a whole value of the users local currency. For example, if the text of the field is $13.37, this method will return a Long with a value of 1337, as penny is the lowest denomination for USD.

It is the responsibility of the calling application to handle this value appropriately. Keep in mind that dividing this number to convert it to some other denomination could possibly result in floating point rounding errors, and should be done with great caution.

To assist with needing to perform work on locale-specific values after retrieval, CurrencyEditText provides the getLocale() method which returns the locale currently being used by that instance for its formatting.

Locales

CurrencyEditText relies on a Locale object to properly format the given value. There are two Locale variables that are exposed via getters and setters on a given CurrencyEditText object: locale and defaultLocale.

locale is the users default locale setting based upon their Android configuration settings. This value is editable by the user in Android settings, as well as via the CurrencyEditText API. Note that this value, when retrieved from the end-users device, is not always compatible with ISO-3166. This is used as the "happy path" variable, but due to the potential lack of ISO-3166 compliance, CurrencyEditText will fall back to defaultLocale in the event of an error.

defaultLocale is a separate value which is treated as a fallback in the event that the provided locale value fails. This may occur due to the locale value not being part of the ISO-3166 standard. See Java.util.Locale.getISOCountries() for a list of supported values. Note that the list of supported values is hard-coded into each version of Java, therefore over time, the list of supported ISO's may change.

The default value for defaultLocale is Locale.US. Both this, and the locale value, can be overwritten using setters found on the CurrencyEditText object. Be very careful to ensure that should you override defaultLocale's value, you only use values supported by ISO-3166, or an IllegalArgumentException will be thrown by the formatter.

Formatting Values

If you'd like to retrieve a formatted version of a raw value you previously accepted from a user, use the formatCurrency() method of CurrencyEditText. It takes one parameter: a string representing the value you'd like to have formatted. It is expected that this value will be in the same format as the returning value from the getRawValue() method. For example:

//rawVal contains "1000"
CurrencyEditText cet = new CurrencyEditText();
 
... user inputs "$10.00"
 
//rawVal is 1000
Long rawVal = cet.getRawValue();

//formattedVal accepts "1000" and returns "$10.00"
String formattedVal = cet.formatCurrency(Long.toString(rawVal));

//or

String formattedVal = cet.formatCurrency(rawVal);

Decimal Digits

By default, the CurrencyEditText text formatter will use the locale object to obtain information about the expected currency. This includes the location of the decimal separator for lower denominations (e.g. dollars vs. cents). If you would like to alter the decimal placement position, you can use the setDecimalDigits() method. This is very useful in some cases, for instance, if you only wish to show whole dollar amounts.

CurrencyEditText cet = new CurrencyEditText();
 
... user inputs 1000
 
//currentText is "$10.00"
String currentText = cet.getText();

cet.setDecimalDigits(0);

//newText is "$1,000"
String newText = cet.getText();

DecimalDigits can also be set in the XML layout if you don't want to obtain a java reference to the view.

Note that the valid range of DecimalDigits is 0 - 340. Any value outside of that range will throw an IllegalArgumentException.

Try it out

This repo contains the currencyedittexttester project which provides a testing application to showcase CurrencyEditText functionality. You're encouraged to pull down and run the app to get a feel for how CurrencyEditText works.

Why doesn't CurrencyEditText do <x>?

CurrencyEditText is designed to be a small, lightweight module to provide ease-of-use to developers. If there is functionality missing that you would like to see added, submit a new Issue and label it as an Enhancement, and I will take a look. I make no guarantees that I will agree to implement it.

Use at your own risk!

As called out in the Apache license (which this project falls under), by using this software you agree to use it AS-IS. I make no claims that this code is 100% bug-free or otherwise without issue. While I've done my best to ensure that rounding errors don't come into play and that all codeflows have been tested, I cannot guarantee or provide any sort of warranty that this code will work for you. The onus is on you, and you alone, to analyze this software and determine if it's featureset and quality meet your needs.

Comments
  • force curser to right, when currecyEditText is focused

    force curser to right, when currecyEditText is focused

    Hi, nice library, thank's for sharing it. Do you know if it's possible to force the curser to the furthest right when the currencyEditText first gets focus?

    As it is at the moment when the user clicks in the editText the curser just appears wherever they clicked, which means the first number they enter will appear at that position, then subsequent numbers will appear on the right. It makes the user experience a little awkward.

    Cheers,

    opened by d34n0s 8
  • Setting new currency does nothing

    Setting new currency does nothing

    I noticed that when calling setCurrency, it'll set it back to the default currency. It's because setCurrency calls init, which calls initCurrency and sets the currency back to the default locale. Basically, trying to set a currency that is not the default currency is impossible because it would set itself back to the default currency. I can't set a locale because I only have a currency.

    myCurrencyEditText.setCurrency(myCurrency); // calling this
    
    public void setCurrency(Currency currency) {
      this.currency = currency;
    
      init(); // goes here
      updateHint();
    }
    
    private void init() {
      initCurrency(); // then here
      initCurrencyTextWatcher();
    }
    
    private void initCurrency() {
      try {
        currency = Currency.getInstance(locale); // effectively sets it back to the default currency
      } catch (IllegalArgumentException e) {
        currency = Currency.getInstance(defaultLocale);
      }
    }
    
    opened by samuelili 6
  • NumberFormatException for number greater than Long max value

    NumberFormatException for number greater than Long max value

    java.lang.NumberFormatException: For input string: "10000000000000000000"
        at java.lang.Long.parseLong(Long.java:593)
        at java.lang.Long.valueOf(Long.java:804)
        at com.blackcat.currencyedittext.CurrencyTextWatcher.afterTextChanged(CurrencyTextWatcher.java:49)```
    opened by benwicks 4
  • CurrencyTextView

    CurrencyTextView

    Is there a TextView exposed by this lib which handles all currency related functionalities just like the EditText does? I am looking to display currency stored in long in a TextView.

    opened by aandis 4
  • SetText(CharSequence text) method passing empty string as parameter doesn't change mText

    SetText(CharSequence text) method passing empty string as parameter doesn't change mText

    Hey! :)

    I've had a problem: calling SetText("") to erase the displayed currency value and then bring the hint again doesn't work like default EditTexts.

    I'm using CurrencyEditText inside my RecyclerView items. When I add a new item, I call SetText("") in my CurrencyEditText object to update it's value (for example, changing mText from "U$0,02" to "", so it would display back again the hint, like a default EditText), but it doesn't change the value.

    Edit: This situation happens inside the afterTextChanged(Editable editable) method of class CurrencyTextWatcher, when it tries to get a formatted text from an empty string: image

    I've converted initCurrencyTextWatcher() from private to public, and called it so It would be possible to reinitialize textWatcher field, and then lastGoodInput would be an empty string in this situation, but the app freezes in this situation.

    Is there any way to force the hint to be displayed?

    opened by miguelfs 4
  • Gradle Error: Failed to resolve: com.github.blackcat27:library:1.0.2-SNAPSHOT

    Gradle Error: Failed to resolve: com.github.blackcat27:library:1.0.2-SNAPSHOT

    Hi,

    first of all, thank you for your work. You seem to be the only one, who made a simple currency EditText for Android.

    Your code does not seem to be available on maven central. I could also not find it by browsing through http://search.maven.org/. So I guess your repository there might have been deleted for some reason. Could you fix this?

    opened by phihos 4
  • Crash when Entering decimal point in a blank field

    Crash when Entering decimal point in a blank field

    Reproduction Steps:

    In the sample app,

    1. Click in Reset button.
    2. Type a decimal point in the first field

    Expected

    1. The string "$0." appears in the field

    Actual

    The app crashes.

    09-23 20:08:43.367 14567-14567/com.blackcat.currencyedittexttester E/AndroidRuntime: FATAL EXCEPTION: main Process: com.blackcat.currencyedittexttester, PID: 14567 java.lang.IndexOutOfBoundsException: setSpan (1 ... 1) ends beyond length 0 at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1265) at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:684) at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:677) at android.text.Selection.setSelection(Selection.java:76) at android.widget.TextView.semSetSelection(TextView.java:11458) at android.widget.TextView.semSetSelection(TextView.java:11472) at android.widget.EditText.setSelection(EditText.java:124) at com.blackcat.currencyedittext.CurrencyTextWatcher.afterTextChanged(CurrencyTextWatcher.java:68) at android.widget.TextView.sendAfterTextChanged(TextView.java:9443)

    opened by adcaine 3
  • Poland currency issue

    Poland currency issue

    For Poland there is an issue because the currency simbol has 2 characters (for euro it is only 1). The code was coming from right to left 2 characters, the euro simbol and the space. I already fixed for my application and I'm going to do a pull request for this fix today.

    opened by LucasEduardo 3
  • Negative numbers not working

    Negative numbers not working

    Hi, I'm trying to use your module but even though I'm including app:allow_negative_values="true" into my xml and the minus sign is shown on my keyboard, it won't allow me to insert negative numbers ( pressing it has no effect). Am I missing something?

    PS: is it really necessary to include InputType.TYPE_NUMBER_FLAG_DECIMAL? Isn't the user supposed to insert only numbers?

    opened by kazkis 3
  • Build problem

    Build problem

    Hi,

    I am new at gradle. I tried to add dependency to my gradle file as " compile 'com.github.blackcat27:library:1.2.0-SNAPSHOT'" and got error

    Error:(33, 13) Failed to resolve: com.blackcat.currencyedittext:library:1.2.0-SNAPSHOT

    What is the problem?

    opened by mehmetyilmaz001 3
  • Problem with Locale.

    Problem with Locale.

    So, my Locale displays well on the Edittext, i save the value as Raw, but when I try to display the formatted Value. it uses US Locale. how can I overcome this constraint?

            CurrencyEditText cet = new CurrencyEditText(context,null);
            String currentText = cet.formatCurrency(Long.toString(produtoActual.getValor()));
            Locale locale = new Locale("pt", "MZ");
            cet.setLocale(locale);
            viewHolder.preco.setText(currentText);
    
    opened by doilio 2
  • Currency sign can't be removed in CurrencyEditText

    Currency sign can't be removed in CurrencyEditText

    I am using this library to format edittext like currency input. Example. if user wants to enter 10, he will simply enter 1000 and we will automatically show the value as 10.00. After I used this library, everything was going well. But, the problem is currency sign (eg.$ sign if my device's locale is US) appears at the start of EditText. I am trying to drop that sign. I have tried android.hint="" like mentioned in README. But, it is not working. I know it is because of Locale. So, I tried to drop locale like below. edCurrency.setDefaultLocale(Locale.ROOT); edCurrency.setLocale(Locale.ROOT); But, it is not also working. Could you please let us know how can I drop currency sign in CurrencyEditText. Thanks and appreciating! image

    opened by Arkar009 1
  • CurrencyEditText setSelection problem

    CurrencyEditText setSelection problem

    Hi, I am trying to place the cursor rightmost position at the first focus. I get the content length correctly and call setSelection method. But doesn't work for me.

    binding.cet.setSelection(binding.cet.getText().length()); // I call it on focus

    opened by yeulucay 5
  • Issue Creating an Instance of CurrencyEditText

    Issue Creating an Instance of CurrencyEditText

    When I call CurrencyEditText cet = new CurrencyEditText() it requires 2 parameters, the context and certain attributes. How do I use These Attributes?

    Thanks in Advance

    opened by doilio 0
  • Removing the currency symbol like the dollar $

    Removing the currency symbol like the dollar $

    Tested with the android.hint="" to remove the $ sign (as is stated in the README), no effect. And since you are using this code for the format: currencyFormatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale); regardless of the hints, I don't see how the currency symbol will be removed.

    Is there any plan to fix this?

    opened by sachen 2
  • Long overflow parsing exception

    Long overflow parsing exception

    When you mash numbers and you overflow the capacity of long, CurrencyTextWatcher line 49 parsing Long from string throws 'java.lang.NumberFormatException: Invalid long: "9658656685598570005"'

    opened by aCanakci 0
Releases(2.0.2)
  • 2.0.1(Jul 14, 2017)

  • 2.0.0(Jul 9, 2017)

    CurrencyEditText 2.0 is here!

    2.0 contains some significant refactoring to the existing solution, including some breaking changes (hence the new major version). Some of the biggest changes include:

    • setLocale will no longer override a caller-specified hint if one was provided

    get/setCurrency removed - Exposing currency was exposing too much implementation detail for not enough gain. The currency class is only used by the formatter to obtain the decimal digit location. Therefore, this information is now exposed directly through a new API.

    new API int getDecimalDigits() and setDecimalDigits(int digits)` - Allows the user to specify how many decimal digits should be shown, overriding the users locale formatting. This is primarily useful for showing only whole-number values (e.g. $100 instead of $100.00). This value can also be set via an XML layout attribute.

    new API configureViewForLocale(Locale locale) - This is the new primary mechanism for overriding the users device locale should you need to do so. While you can still manually set the locale via setLocale(), this method will also handle decimal digit calculations, hint updates, refresh the view, etc.

    new API setValue(long value) - takes a long and handles formatting and populating the view, rather than callers having to call formatCurrency() and setText() themselves.

    max length restriction lifted - The old limit of 15 characters is gone thanks to updates in how the formatter is set up.

    better test coverage - Additional tests to provide better code coverage, as well as new testing libraries to facilitate additional testing moving forward.

    test app greatly enhanced to showcase more features - Several new views have been added to the Test app to allow developers to get a better idea of how CurrencyEditText works and what's going on 'under the hood'.

    Additionally, several open issues were closed out.

    My apologies for allowing this library to sit idle for so long. I'm going to make a conscious effort to give this tool more attention moving forward. Thanks to everyone that uses it and provides feedback.

    Enjoy!

    Source code(tar.gz)
    Source code(zip)
  • v1.3.0(Feb 8, 2016)

Owner
Josh Kitchens
I am a professional C# developer with over 10 years of experience developing a wide range of solutions for both public and governmental agencies.
Josh Kitchens
Android form edit text is an extension of EditText that brings data validation facilities to the edittext.

Android Form EditText Android form edit text is an extension of EditText that brings data validation facilities to the edittext. Example App I built a

Andrea 1.5k Dec 14, 2022
Androids EditText that animates the typed text. EditText is extended to create AnimatedEditText and a PinEntryEditText.

AnimatedEditText for Android This repository contains AnimatedEditText and TextDrawable all of which extend the behaviour of EditText and implement fe

Ali Muzaffar 439 Nov 29, 2022
Add text masking functionality to Android EditText. It will prevent user from inserting not allowed signs, and format input as well.

MaskFormatter MaskFormatter adds mask functionality to your EditText. It will prevent user from inserting not allowed signs, and format input as well.

Azimo Labs 161 Nov 25, 2022
An address-autocompleting text field for Android

android-PlacesAutocompleteTextView An AutocompleteTextView that interacts with the Google Maps Places API to provide location results and caches selec

SeatGeek 283 Dec 28, 2022
Date text field with on the fly validation built with Jetpack Compose.

Date text field with on the fly validation built with Jetpack Compose.

null 15 Nov 16, 2022
An extension of Android's TextView, EditText and Button that let's you use the font of your choice

AnyTextView (deprecated) Note: AnyTextView is no longer being maintained. I recommend replacing AnyTextView with the Calligraphy library instead. Frus

Hans Petter Eide 165 Nov 11, 2022
💰 A library to dynamically format your EditTexts to take currency inputs

CurrencyEditText A library to dynamically format your EditTexts to take currency inputs. Gradle Dependency Add the dependency to your app's build.grad

Cotta & Cush Limited 115 Dec 28, 2022
A library to show emoji in TextView, EditText (like WhatsApp) for Android

Discontinued This projected is discontinued. Please consider using other alternative, i.e EmojiCompat. Contact me if you want to continue working on a

Hieu Rocker 3.6k Jan 5, 2023
Android library contain custom realisation of EditText component for masking and formatting input text

Masked-Edittext Masked-Edittext android library EditText widget wrapper add masking and formatting input text functionality. Install Maven <dependency

Evgeny Safronov 600 Nov 29, 2022
AutosizeEditText for Android is an extension of native EditText that offer a smooth auto scale text size.

AutoscaleEditText AutosizeEditText for Android is an extension of native EditText that offer a smooth auto scale text size. Latest Version How to use

Txus Ballesteros 354 Nov 28, 2022
Form validation and feedback library for Android. Provides .setText for more than just TextView and EditText widgets. Provides easy means to validate with dependencies.

android-formidable-validation Form validation and feedback library for Android. Provides .setText for more than just TextView and EditText widgets. Pr

Linden 147 Nov 20, 2022
Simple way to create linked text, such as @username or #hashtag, in Android TextView and EditText

Simple Linkable Text Simple way to create link text, such as @username or #hashtag, in Android TextView and EditText Installation Gradle Add dependenc

Aditya Pradana Sugiarto 76 Nov 29, 2022
A simple Android Tag EditText

TagEditText A simple Android Tag EditText. Setup The easiest way to add the TagEditText library to your project is by adding it as a dependency to you

HearSilent 15 May 5, 2022
An Android App example of how to create a custom EditText using DoubleLinkedList Data Structure

DoubleLinkedListEditText Library This is a library to create an EditText based on the Doubly Linked List data structure so that the user can enter cod

Layon Martins 1 Nov 9, 2021
Awesome Android Typeahead library - User mention plugin, UI widget for auto complete user mention using the at sign (@) like Twitter or Facebook.

android-typeahead Awesome Android Typeahead library - User mention plugin, UI widget for auto complete user mention using the at sign (@) like Twitter

Arab Agile 11 Jun 4, 2019
A custom EditText with a switchable icon which shows or hides the password

Deprecated This library is deprecated now as there is an official way to use the password toggle with the TextInputLayout (inside the support library

Maksim 430 Nov 20, 2022
A single EditText instead of a classical form. Library that implements flavienlaurent's singleinputform

material-singleinputform A single EditText instead of a classical form. This Library is a library implementation of flavienlaurent's "Single input for

Jan Heinrich Reimer 200 Nov 14, 2022
A single EditText instead of a classical form. Library that implements flavienlaurent's singleinputform

material-singleinputform A single EditText instead of a classical form. This Library is a library implementation of flavienlaurent's "Single input for

Jan Heinrich Reimer 200 Nov 14, 2022
Uma máscara personalizável para EditText, que pode ser adicionada como um TextWatcher.

Custom-Mask-for-EditText ?? ( Máscara personalizável para EditTexts!) Uma máscara customizável que pode ser adicionada aos seus EditTexts, e adaptada

Thyago Neves Silvestre 3 Jun 14, 2022