Reputation: 1092
I want to put specific format while entering value in my edittext.
for example while entering 120000 it automatic set to 1,20,000.00 inmy edit text.
how to set this type of format in text-watcher?
Upvotes: 0
Views: 284
Reputation: 5595
Use a textwatcher as follows:
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;
}
To call the textwathcher you have to do:
edyourdittext.addTextChangedListener(new GenericTextWatcher(edyouredittext));
//this is the edittext with which you want to bind the textwatcher
Upvotes: 1