Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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

like image 607
Dev Avatar asked Oct 27 '25 10:10

Dev


2 Answers

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() {
      @Override
      public void afterTextChanged(Editable s) {
        yourEditText.setText("$" + yourEditText.getText().toString());
      }
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {}
   });
}
like image 93
Logan Rodie Avatar answered Oct 28 '25 23:10

Logan Rodie


My solution unsing kotlin and databinding (but actually the essence is in the text watcher):

XML Part:

 <EditText
        ...
        android:addTextChangedListener="@{viewModel.currencyTextWatcher}"
        android:inputType="number"
        android:digits="$1234567890"
        />

TextWatcher implementation:

val currencyTextWatcher = object : TextWatcher {
    override fun afterTextChanged(editable: Editable?) {
        when {
            editable.isNullOrEmpty() -> return
            Regex("\\$\\d+").matches(editable.toString()) -> return
            editable.toString() == "$" -> editable.clear()
            editable.startsWith("$").not() -> editable.insert(0, "$")
        }
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit 
}
like image 39
Max Diland Avatar answered Oct 29 '25 00:10

Max Diland