我有一个editText
,可以接受用户的电话号码。我的目标是,一旦用户输入电话号码,它应格式化为" X-XXX-XXX-XXX" ,一旦用户长按它将打开拨号器。
我在google上搜索,但是使用此代码找到了像XXX-XXX-XXX这样的格式。
PhoneNumberUtils.formatNumber(字符串)
我如何实现我的欲望输出?
答案 0 :(得分:0)
在xml文件中添加editText,如下所示
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="13"
android:id="@+id/edit"/>
</LinearLayout>
在您的活动中将textchange listner和键更改列表器设置为您的editText
public class MainActivity extends AppCompatActivity {
EditText editor;
boolean isDeletePressed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//X-XXX-XXX-XXX
editor= (EditText) findViewById(R.id.edit);
editor.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String text=s.toString();
if(text.length()==1) {
if(!isDeletePressed) {
editor.setText(editor.getText().toString() + "-");
editor.setSelection(editor.getText().toString().length());
}
}else if(text.length()==2){
if(!(text.charAt(1)=='-')){
editor.setText(editor.getText().toString().substring(0,1)+"-"+editor.getText().toString().substring(1));
editor.setSelection(editor.getText().toString().length());
}
}else if(text.length()==5){
if(!isDeletePressed) {
editor.setText(editor.getText().toString() + "-");
editor.setSelection(editor.getText().toString().length());
}
}else if(text.length()==6){
if(!(text.charAt(5)=='-')){
editor.setText(editor.getText().toString().substring(0,5)+"-"+editor.getText().toString().substring(5));
editor.setSelection(editor.getText().toString().length());
}
}else if(text.length()==9){
if(!isDeletePressed) {
editor.setText(editor.getText().toString() + "-");
editor.setSelection(editor.getText().toString().length());
}
}else if(text.length()==10){
if(!(text.charAt(9)=='-')){
editor.setText(editor.getText().toString().substring(0,9)+"-"+editor.getText().toString().substring(9));
editor.setSelection(editor.getText().toString().length());
}
}
}
});
editor.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
isDeletePressed = (i == KeyEvent.KEYCODE_DEL);
return false;
}
});
}
}