I my application when user enter any numberic value in EditText
then $ append()
before text. Any help would be greatly appreciated...thankss a lot...
Try using a TextWatcher
as follows:
EditText editbox = (EditText)findViewById(R.id.editText1);
editbox.addTextChangedListener(new TextWatcher(){
@Override
public void afterTextChanged(Editable s){
if(s.toString().length() > 0 && s.toString().charAt(0) != '$'){
StringBuilder b = new StringBuilder(s.toString());
b = b.reverse();
b.append('$');
b = b.reverse();
editbox.setText(b);
editbox.setSelection(editbox.getText().length());
}
int counter = 0;
for (int i = 0; i < s.toString().length(); i++) {
if (s.toString().charAt(i) == '$') {
counter++;
}
}
if (counter > 1) {
String str = s.toString().replace("$", "").trim();
str = str.replaceAll("\\s+", "");
StringBuilder b = new StringBuilder(str);
b = b.reverse();
b.append('$');
b = b.reverse();
edit.setText(b);
edit.setSelection(edit.getText().length());
} else {
int spaceCount = 0;
for (int i = 0; i < s.toString().length(); i++) {
if (s.toString().charAt(i) == ' ') {
spaceCount++;
}
}
if (spaceCount > 0) {
String str = s.toString().replace("$", "").trim();
str = str.replaceAll("\\s+", "");
StringBuilder b = new StringBuilder(str);
edit.setText(b);
edit.setSelection(edit.getText().length());
}
}
}
});
Another approach would be to combine a TextWatcher
with a regular expression of some sort.
Use the following code
ed.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
if(ed.getText().toString().length()>1)
{
ed.setText("$"+ed.getText().toString());
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.