在开发我的第一个 Android 计算器应用程序时,我通过意图传递答案成功地更新了新活动中的 TextView,但这需要用户点击返回以执行另一次计算。我正在尝试使 doCalculation 按钮更新 MainActivity 中的简单 TextView 并收到错误消息:
06-22 11:08:17.318: E/AndroidRuntime(31328): 由: java.lang.ClassCastException: android.widget.Button 无法转换为 android.widget.EditText
这是我的代码:
/** Called when the user clicks the Calculate! button */
public void doCalculation(View view) {
// Do something in response to button
int answerInt;
String answer;
EditText numberOne = (EditText) findViewById(R.id.number1);
EditText numberTwo = (EditText) findViewById(R.id.number2);
int numberOnee = Integer.parseInt(numberOne.getText().toString());
int numberTwoo = Integer.parseInt(numberTwo.getText().toString());
answerInt = numberOnee * numberTwoo;
answer = Integer.toString(answerInt);
TextView homeAnswerView = (TextView) findViewById(R.id.homeAnswerView);
homeAnswerView.setTextSize(40);
homeAnswerView.setText(answer);
}
作为参考,以下是成功启动新活动的代码:
// Called when the user clicks the Calculate! button
public void doCalculation(View view) {
// Do something in response to button
int answerInt;
String answer;
Intent intent = new Intent(this, DisplayCalculationActivity.class);
EditText numberOne = (EditText) findViewById(R.id.number1);
EditText numberTwo = (EditText) findViewById(R.id.number2);
int numberOnee = Integer.parseInt(numberOne.getText().toString());
int numberTwoo = Integer.parseInt(numberTwo.getText().toString());
answerInt = numberOnee * numberTwoo;
answer = Integer.toString(answerInt);
intent.putExtra(EXTRA_MESSAGE, answer);
startActivity(intent);
}
更新,XML 供参考:
<EditText
android:id="@+id/number2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="number" />
<EditText
android:id="@+id/number1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="number"
android:singleLine="true" />
<Button
android:id="@+id/calculateBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/number2"
android:layout_alignRight="@+id/number2"
android:layout_below="@+id/number2"
android:layout_marginTop="14dp"
android:onClick="doCalculation"
android:text="Calculate!" />
谢谢你的帮助,-迈克尔