在android studio中我想尝试一个简单的数学检查器。用户将在EditText中输入答案,我在点击按钮时尝试检查此答案。
为方便起见,如果问题是3 + 3,则用户在EditText中输入6,当他们点击按钮时,会出现一个Toast,说明他们是对还是错。
我已经搜索了几个小时的代码,但我是Android Studio的新手,所以不确定我是否正确选择了它。
有人可以帮忙吗?
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class numbers1 extends AppCompatActivity {
EditText userAnswer;
String strInput = "";
Button answer;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numbers1);
answer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String check = userAnswer.getText().toString();
if(check.equalsIgnoreCase("6"))
{
strInput = strInput+","+check;
Toast.makeText(getApplicationContext(), "Correct", Toast.LENGTH_LONG).show();
userAnswer.setText(strInput);
userAnswer.setText("");
}
else {
Toast.makeText(getApplicationContext(), "Not Quite. Try Again.", Toast.LENGTH_LONG).show();
}
});
}
}
答案 0 :(得分:0)
我认为您的代码中缺少以下代码......
userAnswer = (EditText) findViewById(R.id.<edittext_id>);
answer = (Button) findViewById(R.id.<button_id>);
答案 1 :(得分:0)
在几个贡献者的帮助下,注意到我没有正确关闭括号,这里是正确的代码:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class numbers1 extends AppCompatActivity {
EditText userAnswer;
String strInput = "";
Button answer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numbers1);
Button answer = (Button) findViewById(R.id.answer);
final EditText userAnswer = (EditText) findViewById(R.id.userAnswer);
answer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String check = userAnswer.getText().toString();
if(check.equalsIgnoreCase("6"))
{
strInput = strInput+","+check;
Toast.makeText(getApplicationContext(), "Correct", Toast.LENGTH_LONG).show();
userAnswer.setText(strInput);
userAnswer.setText("");
}
else {
Toast.makeText(getApplicationContext(), "Not Quite. Try Again.", Toast.LENGTH_LONG).show();
}
}
});
}
}