我正在使用android studio创建一个简单的数学应用程序。我想从按钮添加减号。我有以下用于butoon的XML代码。
<Button
android:id="@+id/btn_minus"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="@dimen/Bottom_margin"
android:layout_weight="1"
android:gravity="center"
android:padding="@dimen/button_padding"
android:text="@string/minus"
android:textColor="@color/text_color"
android:textSize="30sp"
android:textStyle="bold" />
我的java类中也有这段代码。
btn_minus= (Button) findViewById(R.id.btn_minus);
btn_minus.setOnClickListener(this);
此按钮无效。有什么建议吗?
public void onClick(View view)
{
//button clicked
if(view.getId()==R.id.enter){
//enter button
String answerContent = answerTxt.getText().toString();
if(!answerContent.endsWith("?"))
{
//we have an answer}
int enteredAnswer = Integer.parseInt(answerContent.substring(2));
int exScore = getScore();
if(enteredAnswer==answer){
//correct
scoreTxt.setText("Score: "+(exScore+1));
response.setImageResource(R.drawable.correct);
response.setVisibility(View.VISIBLE);
}else{
//incorrect
scoreTxt.setText("Score: 0");
response.setImageResource(R.drawable.wrong);
response.setVisibility(View.VISIBLE);
}
chooseQuestion();
}}
else if(view.getId()==R.id.clear){
//clear button
answerTxt.setText("= ?");
}
else {
//number button
response.setVisibility(View.INVISIBLE);
int enteredNum = Integer.parseInt(view.getTag().toString());
if(answerTxt.getText().toString().endsWith("?"))
answerTxt.setText("= "+enteredNum);
else
answerTxt.append(""+enteredNum);
}
}
这是我得到的错误的logcat。
--------- beginning of crash
02-23 13:49:53.586 3996-3996/com.example.administrator.braintraininggame E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.administrator.braintraininggame, PID: 3996
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.example.administrator.braintraininggame.PlayGame.onClick(PlayGame.java:459)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
答案 0 :(得分:0)
减号不是一个整数,它会在解析为整数时崩溃
最好只添加以下代码:
else if(view.getId()==R.id.btn_minus){
//minus button
// substract the value
}