【发布时间】:2014-12-29 12:11:27
【问题描述】:
我想在编辑文本中输入值时输入特定格式。
例如,当输入 120000 时,它会在我的编辑文本中自动设置为 1,20,000.00。
如何在 text-watcher 中设置这种格式?
【问题讨论】:
标签: android android-edittext format
我想在编辑文本中输入值时输入特定格式。
例如,当输入 120000 时,它会在我的编辑文本中自动设置为 1,20,000.00。
如何在 text-watcher 中设置这种格式?
【问题讨论】:
标签: android android-edittext format
按如下方式使用文本观察器:
private class GenericTextWatcher implements TextWatcher{
private View view;
private GenericTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
switch(view.getId()){
case R.id.ed_youredittextid://this is your xml id
insertCommaIntoNumber(ed_youredittextid,s);
break;
}
}
public void afterTextChanged(Editable editable) {
}
}
private void insertCommaIntoNumber(EditText etText,CharSequence s)
{
try {
if (s.toString().length() > 0)
{
String convertedStr = s.toString();
if (s.toString().contains("."))
{
if(chkConvert(s.toString()))
convertedStr = customFormat("###,###.##",Double.parseDouble(s.toString().replace(",","")));
}
else
{
convertedStr = customFormat("###,###.##", Double.parseDouble(s.toString().replace(",","")));
}
if (!etText.getText().toString().equals(convertedStr) && convertedStr.length() > 0) {
etText.setText(convertedStr);
etText.setSelection(etText.getText().length());
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public String customFormat(String pattern, double value) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
return output;
}
public boolean chkConvert(String s)
{
String tempArray[] = s.toString().split("\\.");
if (tempArray.length > 1)
{
if (Integer.parseInt(tempArray[1]) > 0) {
return true;
}
else
return false;
}
else
return false;
}
要调用 textwatcher,您必须这样做:
edyourdittext.addTextChangedListener(new GenericTextWatcher(edyouredittext));
//this is the edittext with which you want to bind the textwatcher
【讨论】: