2011-09-21 141 views
0

我有這個android代碼。我有我的佈局在xml文件中定義的按鈕。我想設置按鈕的文本在這裏通過獲取它的ID。但應用程序的力量關閉。whats錯?安卓應用程序部隊關閉

package com.action ; 
    import android.app.Activity; 
    import android.os.Bundle; 
    import android.widget.Button; 

    public class ActionActivity extends Activity { 
    @Override 
    public void onCreate(Bundle i){ 
     super.onCreate(i); 
     Button button=(Button) findViewById(R.id.but); 
     button.setText("Hey!!"); 
     setContentView(R.layout.main); 
     } 
} 

日Thnx ...

+1

發佈logcat的輸出。 – richardwiden

回答

5

你必須使用findViewById()前使用setContentView(R.layout.main);

如果你不這樣做,findViewById()將返回null(因爲與ID沒有視圖是在當前佈局),試圖把對TextView文字時,你會得到一個NullPointerException

onCreate()正確的版本應該是這樣的:

public void onCreate(Bundle i) { 
    super.onCreate(i); 

    setContentView(R.layout.main); 
    Button button = (Button) findViewById(R.id.but); 
    button.setText("Hey!!"); 
} 
+0

thnx ...我的壞,親愛的自己做這個.... – karyboy

3

看跌的setContentView(R.layout.main)創建按鈕的實例之前。 像這樣:設置findViewById(R.id.but)之前

setContentView(R.layout.main); 

    Button button=(Button) findViewById(R.id.but); 
    button.setText("Hey!!"); 
0

你必須把的setContentView(R.Layout.main)。因爲它會產生空指針異常。

相關問題