Narasimha Narasimha - 6 months ago 167
Android Question

how can automatically format phone number entering edit text in android

In my application I am enter in to phone number in dialog box,in edit text enter in mobile number automatically added into "-" example:999-999-9999 this phone number format

final EditText text= (EditText)myDialog.findViewById(com.fitzgeraldsoftware.mobitrack.presentationlayer.R.id.Tv2);
text.addTextChangedListener(new TextWatcher() {

public void onTextChanged(CharSequence s, int start, int before, int count) {

boolean flag = true;
String eachBlock[] = text.getText().toString().split("-");
// Log.v("11111111111111111111","aa"+flag);
for (int i = 0; i < eachBlock.length; i++)
{
Log.v("11111111111111111111","aa"+i);
if (eachBlock[i].length() > 3)
{
// Log.v("11111111111111111111","cc"+flag);
flag = false;
}
}
if (flag) {
// Log.v("11111111111111111111","dd"+flag);
text.setOnKeyListener(new OnKeyListener() {

public boolean onKey(View v, int keyCode, KeyEvent event) {

if (keyCode == KeyEvent.KEYCODE_DEL)
// Log.v("11111111111111111111","ee"+keyDel);
keyDel = 1;
return false;
}
});

if (keyDel == 0) {

if (((text.getText().length() + 1) % 4) == 0)
{
Log.v("11111111111111111111","bb"+((text.getText().length() + 1) % 4));
if (text.getText().toString().split("-").length <= 2)
{
// Log.v("11111111111111111111","ff"+text.getText().length());
text.setText(text.getText() + "-");
text.setSelection(text.getText().length());
}
}
Log.v("11111111111111111111","cc"+text.getText().length());
a = text.getText().toString();
} else
{
Log.v("11111111111111111111","dd"+a);
a = text.getText().toString();
keyDel = 0;
}

} else {
Log.v("11111111111111111111","ee"+a);
text.setText(a);
}

}

public void beforeTextChanged(CharSequence s, int start, int count,int after)
{
// TODO Auto-generated method stub

}

public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub

}


});


output is :
999-999-999

how can handle exact output is 999-999-9999(3digits-3digits-4digits)

please forward some solution.

Answer

Try an input filter. I haven't tested it out, but something like this should work.

text.setFilters(android.text.method.DialerKeyListener).

See also

android.text.method.DialerKeyListener

TextView.setFilters