大家,我是android开发的新手。现在我有一个自己无法解决的问题。下面的代码有什么问题(尤其是代码中标记的行)?
MainActivity.java:
package com.amaker.ch02.app;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private TextView displayTextView = (TextView)findViewById(R.id.DisplayTextView); <--Possibly this line
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayTextView.setText("change in the code");
}
}
运行,我在 AVD 中收到一条消息:应用程序已意外停止。请再试一次。但是,如果我在声明后不立即分配 displayTextView,IOW 我将代码更改如下,那么一切顺利。
package com.amaker.ch02.app;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private TextView displayTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayTextView = (TextView)findViewById(R.id.DisplayTextView);
displayTextView.setText("change in the code");
}
}
为什么?这两个代码有区别吗?