Reputation: 43
I have layout in my application like below: When i enter 100 from soft keyboard in edit text it should show correct answer toast automatically and it should allow only 3 numbers to enter in input text.
How to do this?
10 x 10 = ___
i tried with Textwatcher but its not working. When i enter correct answer EditText 10 X 10 should change to next value.
int min = 0;
int max = 20;
Random r = new Random();
int mRandomOne = r.nextInt(max - min + 1) + min;
int mRandomTwo = r.nextInt(10 - 0 + 1) + 0;
mFillAnswer = (EditText) findViewById(R.id.fill);
mFillAnswer.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) {
int a = Integer.parseInt(mOneValue.getText().toString());
int b = Integer.parseInt(mTwoValue.getText().toString());
int val = Integer.parseInt(mFillAnswer.getText().toString());
if (val == (a * b)) {
mOneValue.setText(String.valueOf(mRandomOne));
mTwoValue.setText(String.valueOf(mRandomTwo));
}
}
@Override
public void afterTextChanged(Editable s) {
mOneValue.setText(String.valueOf(mRandomOne));
mTwoValue.setText(String.valueOf(mRandomTwo));
}
});
Upvotes: 0
Views: 1543
Reputation: 463
For allowing only 3 numbers use android:maxLength="3"
in your EditText
For automatically detecting the correct or incorrect answer use TextWatcher
Update To change the TextView values:
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//To avoid exception
if(mFillerAnswer.getText().toString().equals("")){return;}
int a = Integer.parseInt(mOneValue.getText().toString());
int b = Integer.parseInt(mTwoValue.getText().toString());
int val = Integer.parseInt(mFillAnswer.getText().toString());
if (val == (a * b)) {
//generate and use Random numbers here
mOneValue.setText(r.nextInt(max - min + 1) + min);
mTwoValue.setText(r.nextInt(10 - 0 + 1) + 0);
//to clear edit text
mFillAnswer.setText("")
}
}
You were generating random numbers only once so it was pointless to be expecting newer values while the generation code is outside the TextWatcher scope
Upvotes: 2