如果沒有下面這兩行代碼就正常運行,但是加上應用就會崩潰。
EditText convertValue = (EditText) findViewById(R.id.et_value_convert);
TextView convertResult = (TextView) findViewById(R.id.txt_result);
完整代碼如下:
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>
問題出在你的初始化控件是在onCreate之前,在onCreate方法中有這麼一句setContentView(R.layout.activity_converter);意思是將布局加載進來,而你的控件是在布局文件中的,你布局文件都沒有加載進來findViewById怎麼可能找得到控件呢?
所以應該改成
public class ConverterActivity extends Activity {
EditText convertValue ;
TextView convertResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_converter);
convertValue = (EditText) findViewById(R.id.et_value_convert);
convertResult = (TextView) findViewById(R.id.txt_result);
}