Dev Dev - 4 months ago 74
Android Question

Adding Dollar Sign ($) Automatically In Edit Text for Android Studio

I would like to have an edit text that would automatically input a dollar sign before the number. Android Studio

Example
$500

EDIT:

The addition of the $ should take place when the edit text is used (when tapped). The Currency will be in CAD. However the dollar sign will act as a reminder for what the field is

Answer

Just add an onChange listener and insert the $ after the user is done input.

private EditText yourEditText;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    yourEditText = (EditText) findViewById(R.id.yourEditTextId);

    yourEditText.addTextChangedListener(new TextWatcher() {

      public void afterTextChanged(Editable s) {
        yourEditText.setText("$" + yourEditText.getText().toString());
      }

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

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