how to make edittext input can't be started with zero? example: 01000 or 0987654321 so on , or we input some value first , example 98124723475 then we add zero(0) in front 098124723475. i am making an app to calculate some prices this bugged me. Suppose the user found this, the edittext is able to input "0" that's bad.
Asked
Active
Viewed 3,182 times
0
-
Related, possibly duplicate: http://stackoverflow.com/q/3349121/102937 – Robert Harvey Feb 26 '15 at 05:12
-
i don't think its related to this, that one talking about characters limitation. Are you implying to tell me to use intent filter? – george samuel Feb 26 '15 at 08:07
5 Answers
5
Implement addTextChangedListener for editText and check the entered text start with zero or not, like:
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String enteredString = s.toString();
if (enteredString.startsWith("0")) {
Toast.makeText(Activity.this,
"should not starts with zero(0)",
Toast.LENGTH_SHORT).show();
if (enteredString.length() > 0) {
editText.setText(enteredString.substring(1));
} else {
editText.setText("");
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});

Ramesh
- 526
- 3
- 14
3
You can do this through check that entry start woth 0 or not using this.
edittext.getText().toString().startsWith("0");
using this if condition is true than display Toast msg or execute what u want.
And you can also use TextWatcher with Edittext. using this u can check every time that user entered 0 or not.

Dharmesh Baldha
- 820
- 6
- 11
2
listen for the Key Stroke event for the EditText and check the keypressed to 0. or
*yourEditText.getText().toString().startsWith("0");*
This might work on button click

Vishnu T B
- 118
- 3
- 15
2
Just do this dude..
editText.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) {
if (editText.getText().toString().startsWith("0"))
editText.setText(editText.getText().toString().substring(1));
}
@Override
public void afterTextChanged(Editable s) {
}
});

Sjd
- 1,261
- 1
- 12
- 11
1
I have the some problem. Fix with this
et.addTextChangedListener(new TextWatcher() {
@Override
//...
@Override
public void afterTextChanged(Editable s) {
String text = s.toString();
int len = s.toString().length();
if (len > 1 && text.startsWith("0")) {
s.replace(0,1,"");
}
}
});

aotian16
- 767
- 1
- 10
- 21