I have a EditText, where I need to enter price. I need to show $ symbol before the digits and two decimal after period(.55) and period should be once. I used the following code. But when I hit "." it doesn't appear in the EditText.
<EditText
android:id="@+id/editTextForAddItemPrice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="20dp"
android:inputType="numberDecimal"
android:digits="0123456789.,$"
android:layout_marginTop="20dp"
android:layout_toRightOf="@+id/textForAddItemPrice"
android:background="@color/app_bg_color"
android:gravity="right"
android:textColor="@color/txt_color_gray"
android:textSize="17dp" />
editTxtForPrice.addTextChangedListener(new TextWatcher() {
boolean isEdiging;
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// String sText = editTxtForPrice.getText().toString();
if(s.length()>0)
{
if(isEdiging) return;
isEdiging = true;
String str = s.toString().replaceAll( "[^\\d]", "" );
if(!str.equals(""))
{
double s1 = Double.parseDouble(str);
NumberFormat nf2 = NumberFormat.getInstance(Locale.ENGLISH);
((DecimalFormat)nf2).applyPattern("$ ###,###.###");
s.replace(0, s.length(), nf2.format(s1));
}
isEdiging = false;
}
}
});
I used a textwatcher, which solved my problem.
editTxtForPrice.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
if (!s.toString().equals(current)) {
editTxtForPrice.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,.]", "");
double parsed = Double.parseDouble(cleanString);
String formatted = NumberFormat.getCurrencyInstance()
.format((parsed / 100));
current = formatted;
editTxtForPrice.setText(formatted);
editTxtForPrice.setSelection(formatted.length());
editTxtForPrice.addTextChangedListener(this);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments