英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论