作者wa007123456 (大笨羊)
看板AndroidDev
標題[問題] OnCreate() 無法對物件初始化
時間Wed May 28 18:20:03 2014
大家好 小弟剛學Android兩天
現在只了解了一些皮毛的基本概念
但我想問一下
我在OnCreate寫了這段程式:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sname=(EditText)findViewById(R.id.surName); //初始化物件
fname=(EditText)findViewById(R.id.firstName); //初始化物件
phone=(EditText)findViewById(R.id.phone); //初始化物件
txv=(TextView)findViewById(R.id.txv); //初始化物件
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
然後 又在MainActivity類別新增了一個方法
public void On(View v){
txv.setText(sname.getText().toString()+fname.getText()+"的電話是"+
phone.getText());
}
我四個物件 都是在類別的範疇裡面 (sname txv fname phone)
但是我發現 只要我使用了On函式 就會當掉
Debug的結果是因為那四個物件的參照是null
後來我又把初始化的過程放到On()方法裡面
就可以執行了
所以我想問 OnCreate 是否不能進行物件的初始化呢?
感謝各位前輩的回答
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.231.86.40
※ 文章網址: http://www.ptt.cc/bbs/AndroidDev/M.1401272407.A.7F9.html
推 givemepass:在哪使用on 05/28 19:47
Button 的 onclick 屬性加上去的
推 cooper6334:跟#1JX49FxT一樣,要先setContentView才能findViewByID 05/29 03:21
→ cooper6334:看起來應該是在onCreate之前就先call On了 05/29 03:22
→ cooper6334:剛沒看清楚,你onCreate本身應該是正常的 05/29 03:25
謝謝你:) 我知道這個 一定要等layout設定完成才能call id
※ 編輯: wa007123456 (61.231.89.5), 05/29/2014 14:44:48
→ visor:你那四個物件應該在 R.id.container 裡面吧 ? 05/30 14:55
→ visor:把那四個初始化動作移到 fragment 後面試試看 05/30 14:56