开发我的第一个Android计算器应用程序时,我成功地通过传递意图来更新新活动中的TextView,但这需要用户点击“返回”才能进行另一个计算。我试图使doCalculation按钮更新MainActivity中的简单TextView,并出现以下错误:
06-22 11:08:17.318: E / AndroidRuntime(31328):Caused by: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!" />
感谢您的帮助, -迈克尔
EditText R.id
的源代码会将我带到EditText
。虽然这绝对不是IDE缓存问题。我所做的是更改LinearLayoutandroid:layout_width="fill_parent" android:layout_height="fill_parent"
为android:layout_width="match_parent" android:layout_height="match_parent"
由于某种原因,它解决了这个问题(我将整个布局包装在其他东西中,最近才删除)。 - D.Ginzbourg