How can I set a limit of number on EditText
?
Like maximum number it's 30, from 31 set a Toast
?
This is an answer if you want to detect if there's more than 30 characters
First of all I recommend to you to set it on your .xml
file as follows :
<EditText
android:id="@+id/someId"
android:maxLength="30"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
Then in your onCreate()
you have to initialize it do it as follows :
EditText eText = (EditText)findViewById(R.id.someId);
Now you have to add Filters
to it as follows:
eText.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(30)
});
And finally you add a TextWatcher()
to deal with it as follows:
eText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(count >= 30) Toast.makeText(MainActivity.this, "Max length of EditText is "+ String.valueOf(30), Toast.LENGTH_SHORT).show();
}
@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
}
});
There's an answer to detect if user tries to put a number higher than n
Your question is quite difficult to understand, but yes, finally I got you, you lucky that I did something similar a year ago...
You first create this inner class
called Max30TextWatcher
(or whatever name)
public class Max30TextWatcher implements TextWatcher {
private EditText et;
Max30TextWatcher(EditText et) {
this.et = et;
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if(TextUtils.isEmpty(editable.toString())){
return;
}
try {
if (Integer.valueOf(et.getText().toString()) > 30) {
Toast.makeText(MainActivity.this, "Max is 30 dawg", Toast.LENGTH_SHORT).show();
//put all the TextView ""
et.setText("");
}
}
catch(NumberFormatException e){
//no dots and comma accepted
et.setText("");
}
}
}
So you change the .xml
to this :
<EditText
android:id="@+id/someId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="2" />
And you call the new class as follows :
et = (EditText)findViewById(R.id.someId);
et.addTextChangedListener(new Max30TextWatcher(et));
And you are done, you cannot put a number higher than 30 :)
Happy coding!
You can add a onTextChangeListener
on EditText
and inside onTextChanged
, you can check if number entered is greater than 30 or not. If it is greater than 30, you can display the Toast
with appropriate message and then clear the text of the EditText
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With