現象:Activity 啟動即崩潰,Logcat 指向 findViewById 行拋出 NullPointerException。
public class ConverterActivity extends Activity {
// 錯誤:在成員變量初始化時調用 findViewById
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); // 佈局在此後加載
// ...
}
}
onCreate() **之前**(構造函數階段)。setContentView() 尚未調用,**視圖樹不存在**,findViewById() 返回 null。setText())觸發 NPE。public class ConverterActivity extends Activity {
// 1. 只聲明,不初始化
private EditText convertValue;
private TextView convertResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 2. 先加載佈局
setContentView(R.layout.activity_converter);
// 3. 再查找控件
convertValue = findViewById(R.id.et_value_convert);
convertResult = findViewById(R.id.txt_result);
// ...
}
}
build.gradle
android {
buildFeatures { viewBinding = true }
}
Activity 中
private ActivityConverterBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityConverterBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// 直接使用 binding.etValueConvert, binding.txtResult
binding.btnToCel.setOnClickListener(v -> {
String input = binding.etValueConvert.getText().toString();
// ...
});
}
findViewById / ViewBinding.inflate 必須在 setContentView 之後調用。
牢記初始化順序,或全面遷移 ViewBinding,徹底杜絕此類崩潰。