从edittext获取用户输入,并在输入正确后立即更改textview(Android)

时间:2014-03-04 17:56:51

标签: java android android-edittext

我有两个文本视图和一个EditText。在TextViews中,它们是随机生成的整数。我想在editText(没有OK按钮)中输入正确时,两个textview更改为新的随机整数。

我已经拥有:

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("!");
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码块来检查编辑文本中的数据是否已设置为正确值,现在应更新textview

@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) {}
   });
}

}