olivier
olivier

Reputation: 2645

Get the user input from edittext and as soon the input is correct change textview (Android)

I have two text views and a EditText. In the TextViews are integers they are random generated. I want when the entry is correct in editText (Without OK button) the two textview change to new random integers.

I already have:

Random random1 = new Random(); int rand = random1.nextInt(100);
Random random2 = new Random();
int rand1 = random2.nextInt(100);
final TextView textview1 = (TextView)findViewById(R.id.textView1);
textview1.setText(String.valueOf(rand));
final TextView textview2 = (TextView)findViewById(R.id.textView2);
textview1.setText(String.valueOf (rand1));
final EditText edittext = (EditText)findViewById(R.id.editText1);
int f = -1; // or other invalid value
if (edittext.getText().toString().length() > 0) {
    f = Integer.parseInt(edittext.getText().toString());
}
int answer = rand1 + rand;
if (f == answer) {
    textview1.setText(rand++);
    textview2.setText(rand1++);
}else {
    System.out.println("!");
}

Thanks for your Help!

Upvotes: 0

Views: 111

Answers (1)

Ravinder Bhandari
Ravinder Bhandari

Reputation: 2636

you can use the following block of code to check if the data in edit text has been set to correct value and now textview should be updated

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    yourEditText = (EditText) findViewById(R.id.yourEditTextId);

    yourEditText.addTextChangedListener(new TextWatcher() {

      public void afterTextChanged(Editable s) {

        // you can call or do what you want with your EditText here
        yourEditText. ... 

      }

      public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

      public void onTextChanged(CharSequence s, int start, int before, int count) {}
   });
}

}

Upvotes: 1

Related Questions