我有一个EditText,我需要输入价格。我需要在数字前显示$符号,在句点(.55)后显示两个小数,并且句点应为一次。我使用了以下代码。但是当我点击“。”它不会出现在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;
}
}
});
答案 0 :(得分:0)
我使用了textwatcher,它解决了我的问题。
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);
}
}