'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
Solution 1:[1]
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) {}
});
}
Solution 2:[2]
The idea is to allow currency amounts to be entered while keeping the currency format. For example: On the empty input field you enter 1, then the output should be $0.01. If I add another digit (say 0), then the output string should be $0.10. Adding yet another digit (say 5) should yield $1.05. And so forth...
Here's some sample code to add currency formatting to the on text change listeners for an edittext field.
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import java.text.DecimalFormat;
import java.text.ParseException;
//This class is for entering currency amount while keeping the right format as the user enters values
public class NumberTextWatcher implements TextWatcher {
private final DecimalFormat dfnd;
private final EditText et;
public NumberTextWatcher(EditText editText) {
dfnd = new DecimalFormat("#,##0.00");
this.et = editText;
}
@Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
//After all the text editing, if there is a string to validate - format it
if (s != null && !s.toString().isEmpty()) {
try {
//Take the input string and remove all formatting characters
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "").replace("$","").replace(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()), "");
//Pass the altered string to a number
Number n = df.parse(v);
//Get the decimal point correct again
n = n.doubleValue() / 100.0;
//Reformat the text with currency symbols, grouping places etc.
et.setText(dfnd.format(n));
//Add the Dollar symbol ($)
et.setText("$".concat(et.getText().toString()));
//Move the editing cursor back to the right place
et.setSelection(et.getText().length());
} catch (NumberFormatException | ParseException e) {
e.printStackTrace();
}
} else //if the input field is empty
{
et.setText("$0.00");
}
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)
{
}
}
Next you just link this new event listener class to your EditText input field
TextInputEditText mCashAmount = mView.findViewById(R.id.txtInput_CashAmount);
mCashAmount.addTextChangedListener(new NumberTextWatcher(mCashAmount));
Solution 3:[3]
Wrap your EditText and Hint Text inside a view and set custom background on them.
dialog_input.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:background="@drawable/bg_text_border_round_corners"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/_31sdp"
android:fontFamily="@font/sf_pro_text_medium"
android:textStyle="bold"
android:text="£"
android:textColor="@android:color/black"
android:layout_gravity="center"/>
<EditText
android:id="@+id/amount_txt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:textSize="30dp"
android:textStyle="bold"
android:inputType="number"
android:textColor="@android:color/black"
android:background="@android:color/transparent"
android:layout_gravity="center"/>
</LinearLayout>
bg_text_border_round_corners.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@android:color/white" />
<stroke android:width="1dip" android:color="#33000000"/>
<corners android:radius="5dp"/>
</shape>
Output from my dialog
Solution 4:[4]
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
}
Solution 5:[5]
Just add the setOnFocusChangeListener on editext and based on focus show/hide the dollar sign.
check the below kotlin code.
edtTransferAmount.setOnFocusChangeListener { _, hasFocus ->
if(hasFocus){
if(edtTransferAmount.text.isEmpty()){
edtTransferAmount.setText("$ ")
}
}else{
if (edtTransferAmount.text.length <= 2){
edtTransferAmount.setText("")
}
}
}
if you want to prevent the dollar sign from clearing.
edtTransferAmount.addTextChangedListener {
if(edtTransferAmount.isFocused){
if(edtTransferAmount.text.length < 2){
edtTransferAmount.setText("$ ")
edtTransferAmount.setSelection(2)
}}
}
Solution 6:[6]
Jetpack Compose solution:
BasicTextField(
value = amount,
onValueChange = { amount = it },
visualTransformation = { text ->
TransformedText(
text = AnnotatedString(text.text + "$"),
offsetMapping = OffsetMapping.Identity
)
}
)
Solution 7:[7]
editText.setText("$");
When user tap on editText then editText prefilled with "$" sign , but the disadvantage of this is that user can able to delete the "$" sign.
Another solution to this problem is that,set editText left drawable to "$" or "$ image".When user triggers an action like save or submit then add "$" before the editText.
String temp = "$";
String finalString = temp + editText.getText().toString();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Bugz |
Solution 3 | AskNilesh |
Solution 4 | Max Diland |
Solution 5 | Jai Khambhayta |
Solution 6 | D.M. |
Solution 7 | Riten |