15

EditTextビューがあり、ユーザーの入力を電話番号形式にフォーマットしたいと思います。たとえば、ユーザーが1234567890と入力すると、最初の3つの数字が入力されるとすぐに、EditTextビューに「(123)456-7890」と動的に表示されます。

OnCreateで次のことを試しましたが、何もしなかったようです...

EditText ET = (EditText) findViewById(R.id.add_number);
ET.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

ユーザーの入力を電話番号形式で表示するにはどうすればよいですか?

4

8 に答える 8

44

このコードを使用すると、カスタムTextWatcherを作成し、必要な形式を作成できます。

ET.addTextChangedListener(new PhoneNumberFormattingTextWatcher() {
        //we need to know if the user is erasing or inputing some new character
        private boolean backspacingFlag = false;
        //we need to block the :afterTextChanges method to be called again after we just replaced the EditText text
        private boolean editedFlag = false;
        //we need to mark the cursor position and restore it after the edition
        private int cursorComplement;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //we store the cursor local relative to the end of the string in the EditText before the edition
            cursorComplement = s.length()-ET.getSelectionStart();
            //we check if the user ir inputing or erasing a character
            if (count > after) {
                backspacingFlag = true;
            } else {
                backspacingFlag = false;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // nothing to do here =D
        }

        @Override
        public void afterTextChanged(Editable s) {
            String string = s.toString();
            //what matters are the phone digits beneath the mask, so we always work with a raw string with only digits
            String phone = string.replaceAll("[^\\d]", "");

            //if the text was just edited, :afterTextChanged is called another time... so we need to verify the flag of edition
            //if the flag is false, this is a original user-typed entry. so we go on and do some magic
            if (!editedFlag) {

                //we start verifying the worst case, many characters mask need to be added
                //example: 999999999 <- 6+ digits already typed
                // masked: (999) 999-999
                if (phone.length() >= 6 && !backspacingFlag) {
                    //we will edit. next call on this textWatcher will be ignored
                    editedFlag = true;
                    //here is the core. we substring the raw digits and add the mask as convenient
                    String ans = "(" + phone.substring(0, 3) + ") " + phone.substring(3,6) + "-" + phone.substring(6);
                    ET.setText(ans);
                    //we deliver the cursor to its original position relative to the end of the string
                    ET.setSelection(ET.getText().length()-cursorComplement);

                //we end at the most simple case, when just one character mask is needed
                //example: 99999 <- 3+ digits already typed
                // masked: (999) 99
                } else if (phone.length() >= 3 && !backspacingFlag) {
                    editedFlag = true;
                    String ans = "(" +phone.substring(0, 3) + ") " + phone.substring(3);
                    ET.setText(ans);
                    ET.setSelection(ET.getText().length()-cursorComplement);
                }
            // We just edited the field, ignoring this cicle of the watcher and getting ready for the next
            } else {
                editedFlag = false;
            }
        }
    });

XMLのEditTextの長さを14文字に制限してください

<EditText
    android:id="@+id/editText_phone"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="phone"
    android:lines="1"
    android:maxLength="14"/>
于 2016-01-20T18:21:24.993 に答える
10

ステップ1:ここにXMLファイルの入力フィールドのコードがあります。

 <EditText
    android:id="@+id/editText_phone"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="phone"
    android:lines="1"
    android:maxLength="14"/>

ステップ2:MainFile.javaに追加するコードは次のとおりです

 phoneNo = (EditText)findViewById(R.id.editText_phone);
 phoneNo.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

出力:(123)456-7890のような番号が表示されます

于 2016-12-23T18:18:41.527 に答える
5

これを試して

PhoneNumberFormattingTextWatcher()メソッドが機能していませんでした私は最終的に割り当てを試しました私は解決策を手に入れました

  1. xmlファイルにこれを貼り付けます

    <EditText
    android:id="@+id/editTextId"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:inputType="phone"
    android:digits="0123456789+" />
    
  2. oncreateメソッドにこれを貼り付けます

    final EditText editText = (EditText) findViewById(R.id.editTextId);
    editText.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)
        {
            String text = editText.getText().toString();
            int  textLength = editText.getText().length();
            if (text.endsWith("-") || text.endsWith(" ") || text.endsWith(" "))
                return;
            if (textLength == 1) {
                if (!text.contains("("))
                {
                    editText.setText(new StringBuilder(text).insert(text.length() - 1, "(").toString());
                    editText.setSelection(editText.getText().length());
                }
            }
            else if (textLength == 5)
            {
                if (!text.contains(")"))
                {
                    editText.setText(new StringBuilder(text).insert(text.length() - 1, ")").toString());
                    editText.setSelection(editText.getText().length());
                }
            }
            else if (textLength == 6)
            {
                editText.setText(new StringBuilder(text).insert(text.length() - 1, " ").toString());
                editText.setSelection(editText.getText().length());
            }
            else if (textLength == 10)
            {
                if (!text.contains("-"))
                {
                    editText.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                    editText.setSelection(editText.getText().length());
                }
            }
            else if (textLength == 15)
            {
                if (text.contains("-"))
                {
                    editText.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                    editText.setSelection(editText.getText().length());
                }
            }
            else if (textLength == 18)
            {
                if (text.contains("-"))
                {
                    editText.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                    editText.setSelection(editText.getText().length());
                }
            }
        }
    });
    

出力:- ここに画像の説明を入力してください

于 2017-07-19T07:39:23.020 に答える
2

いくつかの組み合わせを行い、入力タイプを電話に変更してから、正規表現を使用してすべての非数字文字を削除しました。phonenumber = phonenumber.replaceAll( "\ D"、 "");

于 2013-02-04T19:01:46.060 に答える
0

レイアウトで、入力モードを「電話」に設定します

http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputMethod http://developer.android.com/reference/android/text/InputType.html#TYPE_CLASS_PHONE

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="phone" />

これがニーズに合わない場合は、EditTextにリスナーを追加し、キーストロークごとにテキストを手動でフォーマットします。

    editText.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                // format your EditText here
            }
            return false;
        }
    });
于 2013-02-04T18:19:56.970 に答える
0

Javaコードで使用できます

yourEditText.setInputType(InputTytpe.TYPE_CLASS_PHONE)

またはあなたのxmlで

android:inputType="phone"

Java

XML

于 2013-02-04T18:23:33.247 に答える
0

以下のコードを見つけてください:
私はTextWatcherインターフェースを使用して、入力された電話番号を(XXX)XXX-XXXXに動的にフォーマットしました。

UsPhoneNumberFormatter addLineNumberFormatter = new UsPhoneNumberFormatter(edittxtPhoneNo);
edittxtPhoneNo.addTextChangedListener(addLineNumberFormatter);  


public class UsPhoneNumberFormatter implements TextWatcher {
    private EditText etMobile;

    public UsPhoneNumberFormatter(EditText edt) {
        etMobile = edt;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        String text = etMobile.getText().toString();
        int textlength = etMobile.getText().length();

        if (text.endsWith(" "))
            return;

        if (textlength == 1) {
            if (!text.contains("(")) {
                etMobile.setText(new StringBuilder(text).insert(text.length() - 1, "(").toString());
                etMobile.setSelection(etMobile.getText().length());
            }
        } else if (textlength == 5) {
            if (!text.contains(")")) {
                etMobile.setText(new StringBuilder(text).insert(text.length() - 1, ")").toString());
                etMobile.setSelection(etMobile.getText().length());
            }
        } else if (textlength == 6) {
            if (!text.contains(" ")) {
                etMobile.setText(new StringBuilder(text).insert(text.length() - 1, " ").toString());
                etMobile.setSelection(etMobile.getText().length());
            }
        } else if (textlength == 10) {
            if (!text.contains("-")) {
                etMobile.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                etMobile.setSelection(etMobile.getText().length());
            }
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
    }
}
于 2018-06-05T07:35:25.160 に答える
-7

これは、JQueryのvalidate(onkeyupイベント)を使用して実行できるため、入力時に動的なフォーマットを実行できます(熟考するために経験を不快にさせる)-または、RAZORやKnockoutJSなどのMVVMライブラリを使用して実行できます(フィールドを終了するときに) 。

やりたいことの例は、JQueryValidateドキュメントサイトとノックアウトJSサイトの両方にあります。

于 2013-02-04T18:13:32.317 に答える