我正在制作一个测验应用程序。用户必须完成显示屏上显示的短语并在编辑文本中写下汽车的名称,按下按钮后,如果答案正确,编辑文本变为绿色,否则变为红色。如果所有答案都正确(绿色),则 Intent 继续下一个 Activity 。
我在 if 语句编辑文本变红时遇到了一些困难,即使答案是正确的。另外,如果一切正常,如何让 INTENT 继续进行下一个 Activity ,否则它就不会移动?
public class MainActivity extends AppCompatActivity {
EditText et_one_one, et_one_two, et_one_three;
Button buttonCheck;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_one_one = (EditText) findViewById(R.id.et_one_one);
et_one_two = (EditText) findViewById(R.id.et_one_two);
et_one_three = (EditText) findViewById(R.id.et_one_three);
final String t1 = et_one_one.getText().toString();
final String t2 = et_one_two.getText().toString();
final String t3 = et_one_three.getText().toString();
buttonCheck = (Button) findViewById(R.id.buttonCheck);
buttonCheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (t1.equals("maserati")){
et_one_one.setBackgroundColor(Color.GREEN);
}
else {
et_one_one.setBackgroundColor(Color.RED);
}
if (t2.equals("mercedes")){
et_one_two.setBackgroundColor(Color.GREEN);
}
else{
et_one_two.setBackgroundColor(Color.RED);
}
if (t3.equals("bmw")){
et_one_three.setBackgroundColor(Color.GREEN);
}
else{
et_one_three.setBackgroundColor(Color.RED);
}
}
});
}
最佳答案
您每次在 if else 语句中仅更改 et_one_one
的颜色。不应该针对不同的编辑文本吗?
buttonCheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean allAnswersCorrect = true;
String t1 = et_one_one.getText().toString();
String t2 = et_one_two.getText().toString();
String t3 = et_one_three.getText().toString();
if (t1.equals("maserati")){
et_one_one.setBackgroundColor(Color.GREEN);
}
else {
allAnswersCorrect = false;
et_one_one.setBackgroundColor(Color.RED);
}
if (t2.equals("mercedes")){
et_one_two.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_two.setBackgroundColor(Color.RED);
}
if (t3.equals("bmw")){
et_one_three.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_three.setBackgroundColor(Color.RED);
}
if(allAnswersCorrect){
Intent intent = new Intent(YourActivity.this, YourSecondActivity.class);
startActivity(intent);
}
}
});
维护一个 allAnswersCorrect
bool 值来检查你的答案是否正确。如果一切正确,请进行下一个 Activity 。
关于android - 将来自编辑文本的数据与来自 if 语句的数据进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32028123/