【发布时间】:2017-08-18 20:54:20
【问题描述】:
当我提示答案并点击检查应用程序崩溃时 和未显示的吐司。 我该怎么做才能解决这个问题??? 我尝试了 evreyhing,例如删除获取文本,甚至将其放入 if 语句中。我该怎么做才能修复它??? Butaway 它是一个测验应用程序,正如我之前所说的那样,该应用程序的基础是答案检查器无法正常工作。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void theFirst() {
String answer1 = "David Ben Gurion";
EditText text = (EditText) findViewById(R.id.answer_no_1);
text.getText().toString();
if (text.equals(answer1)) {
Context context = getApplicationContext();
CharSequence text1 = "Right";
int duration = Toast.LENGTH_SHORT;
Toast rightToast = Toast.makeText(context, text1, duration);
rightToast.show();
}else {
Context context = getApplicationContext();
CharSequence text2 = "Try Again";
int duration = Toast.LENGTH_SHORT;
Toast wrongToast = Toast.makeText(context, text2, duration);
wrongToast.show();
}
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.quizapp.MainActivity"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30dp"
android:layout_gravity="center"
android:text="The Quiz"
android:layout_margin="16dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Who was the first prime minister of Israel"
android:layout_marginLeft="17dp"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:hint="Answer"
android:id="@+id/answer_no_1"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:text="Show answer"
/>
<Button
android:id="@+id/checkAnswerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="theFirst"
android:text="Check answer" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="12dp"
android:text="hint" />
</LinearLayout>
</LinearLayout>
</ScrollView>`
【问题讨论】:
-
您的
onClick方法需要一个View参数 -public void theFirst(View v)。 -
您正在比较 EditText 和 String
EditText text = (EditText) findViewById(R.id.answer_no_1); text.getText().toString(); if (text.equals(answer1)) { [...]此外,您还没有附加崩溃日志。 -
首先将 public void theFirst() 更改为 public void theFirst(View view) 并在 if(text.equals(answer1) 的 if 条件下设置 if(text.getText().toString())。等于(answer1)