1
全部 - 我一直在为此苦苦挣扎了一段时间,并查看了所有关于此类问题的其他问题,但我无法弄清楚:我有一个edttext字段,需要格式化为货币。我已经尝试了与此有关的所有其他问题中的代码,但无论我尝试什么,都不起作用。以下是我的代码:问题格式化货币编辑文本
EditText text = (EditText)findViewById(R.id.edit_bill);
text.setRawInputType(Configuration.KEYBOARD_12KEY);
text.addTextChangedListener(new TextWatcher(){
EditText text = (EditText)findViewById(R.id.edit_bill);
DecimalFormat dec = new DecimalFormat("0.00");
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
{
String userInput= ""+s.toString().replaceAll("[^\\d]", "");
if (userInput.length() > 0) {
Float in=Float.parseFloat(userInput);
float percen = in/100;
text.setText("$"+dec.format(percen));
text.setSelection(text.getText().length());
}
}
}
});
此代码位于onClick方法中。这是否有所作为(例如,仅当用户单击按钮时,文本才会被格式化)?提前致谢!
['onTextChanged'](http://developer.android.com/reference/android/text/TextWatcher.html#onTextChanged%28java.lang.CharSequence,%20int,%20int,%20int%29)does not像那样工作。你不能修改'onTextChanged'中的文字。 –
好的,那么我如何格式化货币? afterTextChanged? – ninge