初めてのAndroid電卓アプリケーションを開発して、新しいアクティビティのTextViewをインテントで渡すことでTextViewを更新することに成功しましたが、これはユーザーがBackを押す必要があります別の計算を実行する。 doCalculationボタンをMainActivityの単純なTextViewに更新し、エラーを取得しようとしています:android.widget.Buttonをandroid.widget.EditTextにキャストすることはできません
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);
}
UPDATE、参照のための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!" />
はあなたの助けをありがとう、 -Michael
クイック返信ありがとうございます。両方を確認するのはEditTextです。 – Michael
参照のためにXMLコードが追加されました。ボタンのIDは@ + id/calculateBtnです – Michael
XMLファイル全体を表示できますか? – Oleksiy