Friday, August 24, 2012

Android EditText with number format input

Some applications require formatting the EditText's value while typing. I.E., a number that needs to be formatted with decimal and thousands separators.

We've created a little helper class implementing TextWatcher to do just that.

import java.text.DecimalFormat;
import java.text.ParseException;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class NumberTextWatcher implements TextWatcher {
    
    private DecimalFormat df;
    private DecimalFormat dfnd;
    private boolean hasFractionalPart;
    
    private EditText et;
    
    public NumberTextWatcher(EditText et)
    {
        df = new DecimalFormat("#,###.##");
        df.setDecimalSeparatorAlwaysShown(true);
        dfnd = new DecimalFormat("#,###");
        this.et = et;
        hasFractionalPart = false;
    }
    
    @SuppressWarnings("unused")
    private static final String TAG = "NumberTextWatcher";

    @Override
    public void afterTextChanged(Editable s)
    {
        et.removeTextChangedListener(this);
        
        try {
            int inilen, endlen;
            inilen = et.getText().length();
            
            String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
            Number n = df.parse(v);
            int cp = et.getSelectionStart();
            if (hasFractionalPart) {
                et.setText(df.format(n));
            } else {
                et.setText(dfnd.format(n));
            }
            endlen = et.getText().length();
            int sel = (cp + (endlen - inilen));
            if (sel > 0 && sel <= et.getText().length()) {
                et.setSelection(sel);
            } else {
                // place cursor at the end?
                et.setSelection(et.getText().length() - 1);
            }
        } catch (NumberFormatException nfe) {
            // do nothing?
        } catch (ParseException e) {
            // do nothing?
        }
        
        et.addTextChangedListener(this);
    }

    @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 (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
        {
            hasFractionalPart = true;
        } else {
            hasFractionalPart = false;
        }
    }

}

To use it, all you need to do is add a TextChangedListener to the EditText component.

editText.addTextChangedListener(new NumberTextWatcher(editText));


You can get the source code directly from GitHub.



59 comments:

  1. This works perfectly but it does not allow leading zeros after the decimal point
    e.g I can not type 1.000000003
    no zeros can go on after the decimal point
    please fix this

    ReplyDelete
    Replies
    1. Thank you so much Roshka but Paul is right , let me to fix this bug !
      in onTextChanged():
      int index = s.toString().indexOf(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()));
      trailingZeroCount = 0;
      if (index > -1)
      {
      for (index++; index < s.length(); index++) {
      if (s.charAt(index) == '0')
      trailingZeroCount++;
      else {
      trailingZeroCount = 0;
      }
      }

      hasFractionalPart = true;
      } else {
      hasFractionalPart = false;
      }

      then in afterTextChanged():

      if (hasFractionalPart) {
      StringBuilder trailingZeros = new StringBuilder();
      while (trailingZeroCount-- > 0)
      trailingZeros.append('0');
      amount.setText(df.format(n) + trailingZeros.toString());
      } else {
      amount.setText(dfnd.format(n));
      }

      Delete
    2. Thanks for your fix, and thank you Roshka.
      All of the best to you bunch of good people.

      Delete
    3. Hi 109862803127285470647.
      I'm sorry but it doesn't accept 0 (zero) after comma (symbol ,).

      My locale definitions are these:
      private final Locale locale = new Locale("pt", "BR");
      df = new DecimalFormat("##,###,###.##", new DecimalFormatSymbols(locale));
      dfnd = new DecimalFormat("#,###,###", new DecimalFormatSymbols(locale));

      Any help?
      Regards.

      Delete
  2. This is really good just have a problem that is appearing voids and would appear to be #,###.## instead of # ### ##. how can I do this? Thank you very much

    ReplyDelete
  3. Thank you very much...this saved my day

    ReplyDelete
  4. Thank you very much, i'm looking for it.Good man !

    ReplyDelete
  5. Hello, I served very good but if instead you pull me #, ## I want to pull me q #. ##.
    Change "," by "." ??? try changing it in the String but pretended not to recognize me.
    As you can do is ????

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Hi there.
      You gotta use locale. In my case, I have:
      private final Locale locale = new Locale("pt", "BR");
      df = new DecimalFormat("##,###,###.##", new DecimalFormatSymbols(locale));
      dfnd = new DecimalFormat("#,###,###", new DecimalFormatSymbols(locale));
      Then it will work...

      But I have a question below, for it doesn't accept 0 (zero) after comma (symbol ,).
      The correction proposed by 109862803127285470647 didn't work for me.

      Regards.

      Delete
  6. Como puedo haacer para que sea un punto en vez de una coma???

    Ejemplo: 1.85

    Trate cambiando el String pero no resulta, tambien probe poniendo un float pero no me salio tampoco.

    ReplyDelete
  7. Android developers develop apps for android phones. These phones run on the android operating system, and are able to download applications. The apps maximize the usefulness of smart phones.gerald winata gozali

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. This rundown of the most prevalent free Android apps run the entire extent, demonstrating the range and the intensity of free Android apps when all is said in done.
    https://appcloner.app
    https://appcloner.net

    ReplyDelete
  10. Thanks For sharing this Superb article.I use this Article to show my assignment in college.it is useful For me Great Work. appcloner's website

    ReplyDelete
  11. Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. hoverwatch price

    ReplyDelete
  12. At the point when we talk about telephone then in a split second Android come in our psyche, and we realize that Android stage is developing at a hurried rate around the world Bulk SMS Service Provider in Sharjah UAE

    ReplyDelete
  13. Developers can have two versions of an app, a free version and premium version consisting of additional features or even keep in-app purchases option. Placing ads on regularly visited apps can also help earn revenues. A combination of different options is also helpful.Best Mobile App development Companies in UK

    ReplyDelete
  14. Apps Geyser gives you facility to make ad-supported apps and make money through that. It has also a unique feature that make if different through other service provider that is sharing features, sharing of your apps to all major social network.Smart AudioBook Player Download

    ReplyDelete
  15. Usage of third party API: The 3rd party API is a device reliant, and it restricts the procedure of apps across special devices. The cross-platform IDE and SDK limit Android developers to use single API for the different device versions.https://techviola.com/why-people-read-mobile-spy-reviews

    ReplyDelete
  16. The application. should now be introduced effectively on your cell phone and you can utilize it like some other application. itools crack

    ReplyDelete
  17. With Brandsoo, it’s never been easier or more convenient to shop high quality domain names and professional logos that’ll instantly give your brand a leg up company brand names for sale and resonate with your audience! With many different domain sellers all competing for your business, you need to know where your business and brand will see.

    ReplyDelete
  18. Forex Signals, MT4 and MT5 Indicators, Strategies, Expert Advisors, Forex News, Technical Analysis and Trade Updates in the FOREX IN WORLD

    Forex Signals Forex Strategies Forex Indicators Forex News Forex World

    ReplyDelete
  19. Situs judi bola online UFA88 Terpercaya, juga memiliki casino online seperti, baccarat, roulette, Judi slot online, sabung ayam dan Dadu online.

    ReplyDelete
  20. Adam the alien - Animated films A close encounter with a likable robot from another solar system leads to a star-crossed friendship Do aliens exist and an impossible intergalactic mission to save Extraterrestrial life the robot’s friends— despite overwhelming New cartoon movies odds.

    ReplyDelete
  21. TogelResult.info - Adalah Situs data hk Khusus yang menyediakan Daftar keluaran hk Result Nomor Togel dan Data hasil keluaran live draw hk seperti hk sgp sydney yang sudah terpercaya keluaran togel hk.

    ReplyDelete
  22. Website laten maken? Onze professionals bouwen een omzetverhogende, professionele én unieke website of webshop! Een website laten maken kan vandaag nog

    Website laten maken | webdesigner | website freelancer | webdeveloper | webdesigner

    ReplyDelete
  23. Discover antimicrobial protection that’s built-in right into the finish of select TikTok Locksmith Services.

    ReplyDelete
  24. Fire Alarm Houston, a RAB Security company, was founded in 2001. The purpose was to provide the Life Safety System to Houston, Harris County, Fort Bend County and the surrounding areas, a viable alternative to the overgrown nationwide companies. We pride ourselves on being the most trusted, well-rounded and customer-oriented security company in Houston, backed by over seven years of company history and national manufacturer brand names that you know and trust, such as Honeywell.

    ReplyDelete
  25. Fire Sprinkler Texas has been providing fire sprinkler installation, inspection and services for over 30 years in Texas, mainly in the Greater Houston, Dallas, San Antonio or Austin and surrounding area. If you are building a new facility which requires a fire sprinkler system by code, please give us a call for a free consultation.

    ReplyDelete
  26. We are a full service internet marketing company in the Pittsburgh area, that specializes in providing affordable internet marketing solutions for small businesses.
    Our team builds and enhances local business listings and seo search engine optimization. This Pittsburgh SEO company service drives lead generation and brand recognition.
    Our goal is long term mutual relationships with small business owners, providing customized internet marketing services.

    ReplyDelete
  27. Property Adjuster - We specialize in helping families with their property damage claim. Take comfort knowing I will do everything I can to help you. Ask for Mike

    ReplyDelete
  28. Keeping up with Brilyent Kelly. Get Exlcusive offers and see the latest Music and news & Follow me on instragram Celebrity.

    ReplyDelete
  29. Thanks Dev Team for sharing this important information. Waiting for next update.

    online classified ads platform

    ReplyDelete
  30. Thank you for this valuable post. I think we will get more from you.

    The weight of the gypsum panels makes it easy for you to transport from one location or room to another, without having any back problems due to their weight. The large size means that they can fit into rooms like hallways where other pieces may not be appropriate as well because there's plenty of available wall area. To make your house more attractive with gypsum, hire jk gypsum decoration company, they provide best Gypsum Design Price in BD.

    ReplyDelete
  31. So informative post. I was searching like this few day. Thank you.

    Ecotechnology is a specialist, independent and innovative Environmental Testing Company in BD and delivering environmental solutions to private and government sectors.

    ReplyDelete
  32. The first step in any interior-design project is to determine the mood you wish to create in your space. Whether you are trying to convey tranquility and calm or vibrant energy, keeping the mood in mind while you make your design choices will help you create a cohesive look in your room. Hire us for knowing your gypsum design price in BD. We will provide you best prize list.

    ReplyDelete
  33. Get the latest and good quality clothing items Jackets,Coats and Vests Movies, TV Series, Gaming, Casual,Faux Leather and Leather materials available. Gotham Knights Robin Jacket

    ReplyDelete
  34. Diligent security services Offers Security Guard License Training across the province of Ontario. Get Started Today!
    security services
    security guard license online
    shopping mall security
    event security

    ReplyDelete
  35. I love to recommend you Where can crawl Exciting Products latest Jackets, Coats and Vests Click Here Slim Fit Jackets

    ReplyDelete
  36. Nice post. Thank you to provide us this useful information. Monster Energy Jacket

    ReplyDelete
  37. Congratulations on your article, it was very helpful and successful. 7533f815ca72e488656d2b85824ab559
    numara onay
    sms onay
    website kurma

    ReplyDelete
  38. Thank you for your explanation, very good content. c91ab4ab76e4574ae400fc88a95482ce
    altın dedektörü

    ReplyDelete