Reputation: 861
I am trying to limit the edit text value to be less than or equal to 130. In the onCreate method, I did the following:
final EditText expectedYears = (EditText)findViewById(R.id.lifespan);
expectedYears.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count){
if(Integer.parseInt(s.toString())>130){
expectedYears.setText(String.valueOf(130));
}
}
});
I am not really sure why the app crashes after this. By testing, I figured out that the expectedYears.setText
line is causing this. I feel like once I set the text, the onTextChanged function gets called again. How can I fix this?
Stack Trace
at android.widget.EditText.setText(EditText.java:113)
at android.widget.TextView.setText(TextView.java:5209
at net.msolonko.motivation_app.MainActivity$1.onTextChanged(MainActivity.java:49)
at android.widget.TextView.sendOnTextChanged(TextView.java:9364)
at android.widget.TextView.setText(TextView.java:5397)
at android.widget.TextView.setText(TextView.java:5250)
Upvotes: 0
Views: 344
Reputation: 201
setText() method requires string type argument, make sure that you are passing string type argument,can use type casting
Upvotes: 0
Reputation: 96
According to this question, you should not change the text of the EditText being watched in onTextChanged()
. My guess is that it results in an infinite recursion loop.
Instead, try putting your logic setting the text in afterTextChanged()
.
Upvotes: 1