我想在EditText中的每个1,000之间添加逗号,因此用户不必“猜测”它是10,000还是100,000。在EditText中输入数字时,它显示为10000
,但我希望将其显示为10,000
。怎么办?
答案 0 :(得分:5)
您必须将TextChangedListner添加到您的edittext .i.e
et.addTextChangedListener(new TextWatcher() {
@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) {
et.removeTextChangedListener(this);
try {
String givenstring = s.toString();
Long longval;
if (givenstring.contains(",")) {
givenstring = givenstring.replaceAll(",", "");
}
longval = Long.parseLong(givenstring);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String formattedString = formatter.format(longval);
et.setText(formattedString);
et.setSelection(et.getText().length());
// to place the cursor at the end of text
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
et.addTextChangedListener(this);
}
});
注意:确保您的edittext inputtype是数字。即android:inputType =" number"
答案 1 :(得分:0)
使用:
将TextChangedListener附加到EditTexteditText.addTextChangedListener();
请参阅以下 TextWatcher 的javadoc: http://developer.android.com/reference/android/text/TextWatcher.html