Android Edittext Append And Remove Append
Solution 1:
onTextChanged is called everytime you add and remove something. So if your String has length 3, you add your - and the new length is 4. If you press delete (new length is 3 again), onTextChanged is called and - is added again. SO only add something if nothing has been removed from the text.
if (count > before) {
if (count == 3 || count == 7) {
str = str + "-";
} else {
return;
}
input.setText(str);
input.setSelection(input.getText().length());
}
Solution 2:
I was inspired by this answer to achieve what you want:
String mTextValue;
CharactermLastChar='\0'; // init with empty characterint mKeyDel;
myEditText.addTextChangedListener(newTextWatcher() {
@OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {
booleanflag=true;
String eachBlock[] = myEditText.getText().toString().split("-");
for (inti=0; i < eachBlock.length; i++) {
if (eachBlock[i].length() > 4) {
flag = false;
}
}
if (flag) {
myEditText.setOnKeyListener(newView.OnKeyListener() {
@OverridepublicbooleanonKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
mKeyDel = 1;
returnfalse;
}
});
if (mKeyDel == 0) {
if (((myEditText.getText().length() + 1) % 4) == 0) {
myEditText.setText(myEditTex.getText() + "-");
myEditText.setSelection(myEditText.getText().length());
}
mTextValue = myEditText.getText().toString();
} else {
mTextValue = myEditText.getText().toString();
if (mLastChar.equals('-')) {
mTextValue = mTextValue.substring(0, mTextValue.length() - 1);
myEditText.setText(mTextValue);
myEditText.setSelection(mTextValue.length());
}
mKeyDel = 0;
}
} else {
myEditText.setText(mTextValue);
}
}
@OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {
if (s.length()>0) {// save the last char value
mLastChar = s.charAt(s.length() - 1);
} else {
mLastChar = '\0';
}
}
@OverridepublicvoidafterTextChanged(Editable s) {}
});
Solution 3:
I'm rather new to android programming myself. Nevertheless, I think that everytime you call "setText" you are trigging a new onTextChanged event. In my app I remove the listener, set the text and then add the listener again in order to avoid this problem. But for doing this you'll have to save the reference to the TextWatcher.
I.e. given your Activity extends TextWatcher:
edittext.removeTextChangedListener(this);
editText.setText(str);
edittext.addTextChangedListener(this);
You can also put the cursor at the end using:
myedittext.append("");
Post a Comment for "Android Edittext Append And Remove Append"