Reputation: 1697
Now,my EditText only can input number.But I want to ban inputing zero when the zero is the first number. How can I do?
Upvotes: 5
Views: 4403
Reputation: 6102
You can write logic using TextWatcher
. Try to google for textwatcher
.
To start off below is the code snippet.
<textboxobj>.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// Nothing
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Nothing
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Write your stuff here
}
});
Upvotes: 0
Reputation: 646
I tried like this and it works fine!
yourEditText.addTextChangedListener(new TextWatcher(){
public void onTextChanged(CharSequence s, int start, int before, int count)
{
//*** Use the below to lines ****
if (yourEditText.getText().startsWith("0") )
yourEditText.setText("");
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void afterTextChanged(Editable s){}
});
Upvotes: 0
Reputation: 68187
you can achieve this with a TextWatcher:
yourEditText.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) {
String tmp = s.toString().trim();
if(tmp.length()==1 && tmp.equals("0"))
s.clear();
}
});
Upvotes: 0
Reputation: 6128
This will help u
if(edittext.getText().toString().length()== 0 || Integer.valueOf(edittext.getText().toString())== 0){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please enter atleast 1 as value");
builder.setCancelable(true);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
builder.create().show();
}
Upvotes: 1
Reputation: 8702
This should help you:
yourTextEdit.addTextChangedListener(new TextWatcher(){
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (yourTextEdit.getText().matches("^0") )
{
// Not allowed
yourTextEdit.setText("");
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void afterTextChanged(Editable s){}
});
Upvotes: 6