实时编辑用户输入

发布于 2024-10-03 00:39:51 字数 314 浏览 3 评论 0原文

是否可以在用户输入数据时自动将字符插入到 EditText 中?

即,如果用户输入一个长数字,例如 123456789012,当他在编辑文本框中键入该数字时,是否有可能显示该数字,但每 4 个字符有一个破折号?

因此,当您输入上面的数字时,您会看到它被输入到 EditText 框中,但看起来像这样:1234-5678-9012。

目前我有一个应用程序,您可以在其中输入一个长数字,然后按一个按钮,它会为您插入破折号,但我很好奇是否可以在您键入时完成?

非常感谢您的帮助。

Is it possible to auto insert characters into an EditText as the user inputs data?

I.e. if the user is entering a long number such as 123456789012, is it possible for this number to appear as he is typing it in the edit text box, but with a dash every 4th character?

So as you type the number above you would see it being entered in the EditText box but would look like this: 1234-5678-9012.

Currently I have an app where you can enter a long number and then press a button and it inserts the dashes for you, but I'm curious if it could be done as you type?

Many thanks for any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

沫雨熙 2024-10-10 00:39:51

通过标记 android,我认为您正在讨论 android editText,这样您就可以通过监听 TextChangedListener 来做到这一点,

编辑:用于退格

editText.addTextChangedListener(new TextWatcher() {
            int len=0;
            @Override
            public void afterTextChanged(Editable s) { 
                String str = editText.getText().toString(); 
                 if(str.length()==4&& len <str.length()){//len check for backspace 
                    editText.append("-");
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

             String str = editText.getText().toString(); 
              len = str.length();
            }

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


        }); 

By tagging android, I think you are discussing about android editText, is so you can do it by listening the TextChangedListener,

EDITED: for backspace

editText.addTextChangedListener(new TextWatcher() {
            int len=0;
            @Override
            public void afterTextChanged(Editable s) { 
                String str = editText.getText().toString(); 
                 if(str.length()==4&& len <str.length()){//len check for backspace 
                    editText.append("-");
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

             String str = editText.getText().toString(); 
              len = str.length();
            }

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


        }); 
决绝 2024-10-10 00:39:51

为了解决这个问题,我编写了一个类“AutoAddTextWatcher”:

1. 自动在EditText中插入文本。
2. 在EditText中您设定的位置插入文本。
3.当文本长度大于1时,删除EditText中您设置的位置处的文本。

在此处输入图像描述

代码片段:

mEditText_birthday.addTextChangedListener(new AutoAddTextWatcher(mEditText_birthday,
            "/",
            new TextWatcher() {},
            4, 6));

AutoAddTextWatcher 类

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;


/**
 * Created by henry.chuang on 2016/5/12.
 */
public class AutoAddTextWatcher implements TextWatcher {
    private CharSequence mBeforeTextChanged;
    private TextWatcher mTextWatcher;
    private int[] mArray_pos;
    private EditText mEditText;
    private String mAppentText;

    public AutoAddTextWatcher(EditText editText, String appendText, int... position){
        this.mEditText = editText;
        this.mAppentText = appendText;
        this.mArray_pos = position.clone();
    }
    public AutoAddTextWatcher(EditText editText, String appendText, TextWatcher textWatcher, int... position){
        this(editText, appendText, position);
        this.mTextWatcher = textWatcher;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        mBeforeTextChanged = s.toString();

        if(mTextWatcher != null)
            mTextWatcher.beforeTextChanged(s, start, count, after);

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        for (int i = 0; i < mArray_pos.length; i++) {
            if(((mBeforeTextChanged.length() - mAppentText.length() * i) == (mArray_pos[i] - 1) &&
                    (s.length() - mAppentText.length() * i) == mArray_pos[i])){
                mEditText.append(mAppentText);

                break;
            }

            if(((mBeforeTextChanged.length() - mAppentText.length() * i) == mArray_pos[i] &&
                    (s.length() - mAppentText.length() * i) == (mArray_pos[i] + 1))){
                int idx_start = mArray_pos[i] + mAppentText.length() * i;
                int idx_end = Math.min(idx_start + mAppentText.length(), s.length());

                String sub = mEditText.getText().toString().substring(idx_start,  idx_end);

                if(!sub.equals(mAppentText)){
                    mEditText.getText().insert(s.length() - 1, mAppentText);
                }

                break;
            }

            if(mAppentText.length() > 1 &&
                    (mBeforeTextChanged.length() - mAppentText.length() * i) == (mArray_pos[i] + mAppentText.length()) &&
                    (s.length() - mAppentText.length() * i) == (mArray_pos[i] + mAppentText.length() - 1)){
                int idx_start = mArray_pos[i] + mAppentText.length() * i;
                int idx_end = Math.min(idx_start + mAppentText.length(), s.length());

                mEditText.getText().delete(idx_start, idx_end);

                break;
            }

        }

        if(mTextWatcher != null)
            mTextWatcher.onTextChanged(s, start, before, count);

    }

    @Override
    public void afterTextChanged(Editable s) {
        if(mTextWatcher != null)
            mTextWatcher.afterTextChanged(s);

    }

}

完整演示源:
https://github.com/henrychuangtw/AutoInsertEditText

to solve this issue, i write a class "AutoAddTextWatcher" :

1. Auto insert text into EditText.
2. insert text into EditText at positions you are setted.
3. delete text in EditText at positions you are setted, when text length bigger than 1.

enter image description here

code snippet :

mEditText_birthday.addTextChangedListener(new AutoAddTextWatcher(mEditText_birthday,
            "/",
            new TextWatcher() {},
            4, 6));

AutoAddTextWatcher class

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;


/**
 * Created by henry.chuang on 2016/5/12.
 */
public class AutoAddTextWatcher implements TextWatcher {
    private CharSequence mBeforeTextChanged;
    private TextWatcher mTextWatcher;
    private int[] mArray_pos;
    private EditText mEditText;
    private String mAppentText;

    public AutoAddTextWatcher(EditText editText, String appendText, int... position){
        this.mEditText = editText;
        this.mAppentText = appendText;
        this.mArray_pos = position.clone();
    }
    public AutoAddTextWatcher(EditText editText, String appendText, TextWatcher textWatcher, int... position){
        this(editText, appendText, position);
        this.mTextWatcher = textWatcher;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        mBeforeTextChanged = s.toString();

        if(mTextWatcher != null)
            mTextWatcher.beforeTextChanged(s, start, count, after);

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        for (int i = 0; i < mArray_pos.length; i++) {
            if(((mBeforeTextChanged.length() - mAppentText.length() * i) == (mArray_pos[i] - 1) &&
                    (s.length() - mAppentText.length() * i) == mArray_pos[i])){
                mEditText.append(mAppentText);

                break;
            }

            if(((mBeforeTextChanged.length() - mAppentText.length() * i) == mArray_pos[i] &&
                    (s.length() - mAppentText.length() * i) == (mArray_pos[i] + 1))){
                int idx_start = mArray_pos[i] + mAppentText.length() * i;
                int idx_end = Math.min(idx_start + mAppentText.length(), s.length());

                String sub = mEditText.getText().toString().substring(idx_start,  idx_end);

                if(!sub.equals(mAppentText)){
                    mEditText.getText().insert(s.length() - 1, mAppentText);
                }

                break;
            }

            if(mAppentText.length() > 1 &&
                    (mBeforeTextChanged.length() - mAppentText.length() * i) == (mArray_pos[i] + mAppentText.length()) &&
                    (s.length() - mAppentText.length() * i) == (mArray_pos[i] + mAppentText.length() - 1)){
                int idx_start = mArray_pos[i] + mAppentText.length() * i;
                int idx_end = Math.min(idx_start + mAppentText.length(), s.length());

                mEditText.getText().delete(idx_start, idx_end);

                break;
            }

        }

        if(mTextWatcher != null)
            mTextWatcher.onTextChanged(s, start, before, count);

    }

    @Override
    public void afterTextChanged(Editable s) {
        if(mTextWatcher != null)
            mTextWatcher.afterTextChanged(s);

    }

}

complete demo source :
https://github.com/henrychuangtw/AutoInsertEditText

半世蒼涼 2024-10-10 00:39:51
@Override
public void afterTextChanged(Editable s) {

    if(s.length() == 3 && len < s.length()){
        s.append(" - ");
    }

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    len = s.length();
}

这也可以,只有这个代码会在第三个字符后插入 " - "

@Override
public void afterTextChanged(Editable s) {

    if(s.length() == 3 && len < s.length()){
        s.append(" - ");
    }

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    len = s.length();
}

This will do as well, only this code will insert " - " after 3rd character.

翻身的咸鱼 2024-10-10 00:39:51

这就是我

private boolean mInEdit;

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if (!mInEdit) {
        mInEdit = true;
        String delimiter = " - ";
        //Remove chars from your delimiter first
        String digits = s.toString().replaceAll("[- ]", "")
                .replaceAll("\\d{4}", "$0" + delimiter);
        //Handle deletion
        int dLength = delimiter.length();
        if (before > count && digits.endsWith(delimiter.charAt(dLength - 1)) {
            digits = digits.substring(0, digits.length() - dLength);
        }
        mCardNumber.setText(digits);
        mCardNumber.setSelection(mCardNumber.length());
        mInEdit = false;
    }
}

在这里使用的,您可以将分隔符替换为您想要分隔数字的内容。

This is what I used

private boolean mInEdit;

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if (!mInEdit) {
        mInEdit = true;
        String delimiter = " - ";
        //Remove chars from your delimiter first
        String digits = s.toString().replaceAll("[- ]", "")
                .replaceAll("\\d{4}", "$0" + delimiter);
        //Handle deletion
        int dLength = delimiter.length();
        if (before > count && digits.endsWith(delimiter.charAt(dLength - 1)) {
            digits = digits.substring(0, digits.length() - dLength);
        }
        mCardNumber.setText(digits);
        mCardNumber.setSelection(mCardNumber.length());
        mInEdit = false;
    }
}

Here you replace delimiter with what you want to separate digits.

蓬勃野心 2024-10-10 00:39:51

对于那些仍然面临退格键和多个连字符问题的人 -

new TextWatcher() 
{
        boolean hyphenExists;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (s.length() >= 6 && s.charAt(5) == '-') {
                hyphenExists = true;
            } else {
                hyphenExists = false;
            }

            Log.d("TAG", "beforeTextChanged " + s.toString());
        }

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

            Log.d("TAG", "onTextChanged " + s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 5) {
                if (!hyphenExists)
                    s.append('-');
            }
            Log.d("TAG", "afterTextChanged " + s.toString());
        }
    }

For those still facing trouble with backspace and multiple hyphens -

new TextWatcher() 
{
        boolean hyphenExists;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (s.length() >= 6 && s.charAt(5) == '-') {
                hyphenExists = true;
            } else {
                hyphenExists = false;
            }

            Log.d("TAG", "beforeTextChanged " + s.toString());
        }

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

            Log.d("TAG", "onTextChanged " + s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 5) {
                if (!hyphenExists)
                    s.append('-');
            }
            Log.d("TAG", "afterTextChanged " + s.toString());
        }
    }
放肆 2024-10-10 00:39:51

在我的例子中,您可以通过更改文本来实现此目的

,我必须像这样格式化输入: xxx xxx-xxxx

我按照下面给出的方式完成:

etMobileNumber.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {


        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            if (etMobileNumber.text.length == 3 && count != 0) {
                val text = etMobileNumber.getText().toString() + " "
                etMobileNumber.setText(text)
                etMobileNumber.setSelection(text.length)
            } else if (etMobileNumber.text.length == 7 && count != 0) {
                val text = etMobileNumber.getText().toString() + "-"
                etMobileNumber.setText(text)
                etMobileNumber.setSelection(text.length)
            }
        }
    })

结果在打字时非常动态。

输入- 1234567890
结果 - 123 456-7890

You can achieve this with on text changed

in my case, i have to format input like this : xxx xxx-xxxx

i done as given below:

etMobileNumber.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {


        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            if (etMobileNumber.text.length == 3 && count != 0) {
                val text = etMobileNumber.getText().toString() + " "
                etMobileNumber.setText(text)
                etMobileNumber.setSelection(text.length)
            } else if (etMobileNumber.text.length == 7 && count != 0) {
                val text = etMobileNumber.getText().toString() + "-"
                etMobileNumber.setText(text)
                etMobileNumber.setSelection(text.length)
            }
        }
    })

and the result is very dynamic on the go while typing.

input- 1234567890
result - 123 456-7890

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文