因此,每当将这两行注释掉时,它都很好,但随着它们崩溃。
EditText convertValue = (EditText) findViewById(R.id.et_value_convert);
TextView convertResult = (TextView) findViewById(R.id.txt_result);
这是我的完整课程代码,xml 在下面。
package com.doubleelite.maxtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class ConverterActivity extends Activity {
EditText convertValue = (EditText) findViewById(R.id.et_value_convert);
TextView convertResult = (TextView) findViewById(R.id.txt_result);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_converter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_converter, menu);
return true;
}
// Custom method to handle button clicks.
public void onClick(View v) {
switch(v.getId()) {
case R.id.btn_to_cel:
convertResult.setText(String.valueOf(convertFahrenheitToCelsius(Integer.valueOf(convertValue.getText().toString()))));
}
}
private float convertFahrenheitToCelsius(float f) {
return (f-32) * (5/9);
}
private float convertCelsiusToFahrenheit(float c) {
return c * (9/5) + 32;
}
}
这是xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ConverterActivity" >
<EditText
android:id="@+id/et_value_convert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/text_value_convert"
android:inputType="number"
/>
<Button
android:id="@+id/btn_to_cel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button_celsius"
android:onClick="onClick"
/>
<Button
android:id="@+id/btn_to_fahr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button_fahr"
android:onClick="onClick"
/>
<TextView
android:id="@+id/txt_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
tools:ignore="HardcodedText" />
</LinearLayout>