Reputation: 341
i have an edit text and it has numbers and special character like 1234-11222
how can i delete the numbers
and the -
?
i have a code and it works fine for alphabets and numbers but it does not work for special characters.
public void onClick(View v) {
aadrclear.setVisibility(View.INVISIBLE);
String textaddress=addr.getText().toString();
//txtUserName.setText("");
if (textaddress.length() != 0) {
textaddress = textaddress.substring(0, textaddress.length() - 1);
addr.setText(textaddress);
addr.setSelection(textaddress.length());
}
}
i have an edit text...if i enter numbers a - (hyphen)
is placed between 4 numbers.. now if i want to clear using the above code it is not working.. please help
Upvotes: 0
Views: 2946
Reputation: 4971
For adding - every 4 digits use this code snipper
int offset = 0;
textaddress.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) {
// TODO Auto-generated method stub
offset++;
if (textaddress.getText().toString().trim().length() > 0) {
if (offset == 4) {
String result = text_address.getText().toString()
.concat("-");
textaddress.setText(result);
textaddress.setSelection(result.length());
offset = 0;
}
}
}
});
Upvotes: 0
Reputation: 4971
This will be the solution for my understanding over your question.
if(textaddress.getText().toString().trim().length() > 0) {
if(textaddress.getText().toString().charAt(textaddress.getText().toString().trim().length() - 1) != '-') {
String result = textaddress.getText().toString().substring(0,textaddress.getText().toString().length() - 1);
textaddress.setText(result);
textaddress.setSelection(result.length());
}
}
Notify me if it was wrong
EDIT
If u also interested in deleting -
also. Remove the if condition
.
Now the code will be like.
if(textaddress.getText().toString().trim().length() > 0) {
String result = textaddress.getText().toString().substring(0,textaddress.getText().toString().length() - 1);
textaddress.setText(result);
textaddress.setSelection(result.length());
}
Upvotes: 1