Inserting Currency in a Edit Text Field with Text Watcher (Android)

Here is an example of a great way to add a currency in a Edit Text to your layout. As the user types, the numbers will update to add the decimal and the currency symbol.
Screen Shot 2013-11-21 at 4.30.38 PM

 

public class EditSchedule extends Activity {

	EditText amountContribute;

	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.contribution_edit_schedule);

	    amountContribute = (EditText)findViewById(R.id.amount_contribute);

	    amountContribute.addTextChangedListener(tw);
       }
        TextWatcher tw = new TextWatcher() {

	      @Override
	      public void onTextChanged(CharSequence s, int start, int before, int count) {
	      }

	      @Override
	      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	      }

	      @Override
	      public void afterTextChanged(Editable s) {

	        if (!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$")) {
	          String userInput = "" + s.toString().replaceAll("[^\\d]", "");
	          StringBuilder cashAmountBuilder = new StringBuilder(userInput);

	          while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
	            cashAmountBuilder.deleteCharAt(0);
	          }
	          while (cashAmountBuilder.length() < 3) {
	            cashAmountBuilder.insert(0, '0');
	          }
	          cashAmountBuilder.insert(cashAmountBuilder.length() - 2, '.');

	          amountContribute.removeTextChangedListener(this);
	          amountContribute.setText(cashAmountBuilder.toString());

	          amountContribute.setTextKeepState("$" + cashAmountBuilder.toString());
	          Selection.setSelection(amountContribute.getText(), cashAmountBuilder.toString().length() + 1);

	          amountContribute.addTextChangedListener(this);
	        }
	      }
	    };
}

Here is a way you would grab the amount and use it as a float. I had to freestyle this in a blog editor so it is not tested but should be correct. It is bonus material anyways.

Float amount = Float.parseFloat(amountContribute.getText().toString().replace("$" ,"")); 

Graveyard Database Logo

Has everything you want to know about grave yards. Plus has many celebrites and world leaders graves. Pssst it is my other site

Google + Profile
Check out Android Photo Mapping, its a app/site I been working on

  • wholesale nfl jerseys
  • wholesale nfl jerseys china
  • wholesale sports jerseys