通过split函数在EditText中输入时分离数字并保存到Android中的数组中。

huangapple go评论75阅读模式
英文:

Separating numbers through split function while typing in EditText and saving into Arrays in Android

问题

EditText输入的数据将会是像1-3-2-0这样的格式。

使用split函数,我想要将每个由“-”分隔的数字保存在单独的数组中,我已经做到了,但当我开始在EdtTxtInput5中输入时,应用程序崩溃了。

EdtTxtInput5.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) {

        String rapd = EdtTxtInput5.getText().toString();
        String[] Separated =  rapd.split("-");
        String Ropani = Separated[0];
        String Aana = Separated[1];
        String Paisa = Separated[2];
        String Dam = Separated[3];
        EdtTxtInput1.setText(Ropani);
        EdtTxtInput2.setText(Aana);
        EdtTxtInput3.setText(Paisa);
        EdtTxtInput4.setText(Dam);
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});
英文:

I need to separate numbers from an EditText while typing (OnTextChangedListner)

EditText data will be like 1-3-2-0

With split function, I would like to save each numbers separated by "-" in separate array, I've done this, but when i start typing in EdtTxtInput5, application crashes.

EdtTxtInput5.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) {

            String rapd = EdtTxtInput5.getText().toString();
            String[] Separated =  rapd.split("-");
            String Ropani = Separated[0];
            String Aana = Separated[1];
            String Paisa = Separated[2];
            String Dam = Separated[3];
            EdtTxtInput1.setText(Ropani);
            EdtTxtInput2.setText(Aana);
            EdtTxtInput3.setText(Paisa);
            EdtTxtInput4.setText(Dam);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

答案1

得分: 0

onTextChanged 即使输入一个字符也会被触发。这意味着你的分离数组(Separated array)的长度为0。如果你尝试在这个位置之后访问它,程序会崩溃。

如果你想显示这些部分,直到你至少有4个元素。

if (Separated.length >= 4) ...

现在不应该会崩溃。

英文:

onTextChanged will be fired even if you type a single character. This means that your Separated array will have a length of 0. If you try to access it beyond this position it will naturally crash.

If you want to display the parts, do so until you have at least 4 elements.

if (Separated.length>=4) ...

It should not crash now.

huangapple
  • 本文由 发表于 2020年6月6日 00:23:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/62219945.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定