2012-04-10 116 views
0

我正在爲Android創建受歡迎的掃雷遊戲的版本。我試圖以編程方式創建一個按鈕並將其添加到RelativeLayout。我發現非常類似的東西在這裏:How do I programmatically add buttons into layout one by one in several lines?創建一個按鈕並以編程方式將其添加到視圖中

當我嘗試運行它,我在得到一個NullPointerException:

RelativeLayout layout1 = (RelativeLayout) findViewById(R.layout.game); 

這裏是整個代碼塊:

public void create() { 
    RelativeLayout layout1 = (RelativeLayout) findViewById(R.layout.game); 
    for(int i = 0; i < gridSize; i++) { 
     if(grid[i] == 0) { //if grid pos. indicates an empty cell 
      Button empty = new Button(this); 
      empty.setBackgroundResource(R.drawable.emptybutton); //set background to empty 
      empty.setId(i); //set id to value of i 
      empty.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
      layout1.addView(empty); //add the button to the relativeLayout view 
      //((Button) findViewById(i)).setOnClickListener(emptyListener); 
     } 

在此先感謝對於任何迴應

+0

我認爲你的問題無法到達你的game.xml。你能否提供你的結構(大綱)? – guness 2012-04-10 12:11:05

+1

我使用了一個int數組來模擬掃雷領域。例如位置[2]處的值爲9表示在掃雷場區域的位置2處有地雷。那麼我使用if語句來生成不同的按鈕,即如果位置[2] == 9,將創建一個表示礦的按鈕。我試圖將這些按鈕添加到將代表掃雷字段的相對佈局。這有幫助嗎? – DanielFitzgerald123 2012-04-10 13:36:43

回答

2

已將活動的佈局xml設置爲setContentView(R.layout.xxxx)

@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.game); 


... 

RelativeLayout layout1 = (RelativeLayout) findViewById(R.layout.game); 

應該是用於映射控制

RelativeLayout layout1 = (RelativeLayout) findViewById(R.id.relative_id); 

R.id...和RelativeLayout的是一個控制。

+0

是的,我已經設置了內容視圖,我將引用改爲了ID而不是文件名本身,但是當活動開始時仍然看不到任何按鈕。我已經調用了onCreate()方法中的create()方法,是否在調用activity時啓動的onCreate()方法中調用了任何調用? – DanielFitzgerald123 2012-04-10 13:31:44

+0

顯示您的logcat跟蹤。 – 2012-04-10 15:36:18

+0

不再獲得nullpointerexception。如果我打電話給create()方法屏幕只是保持空白,沒有按鈕或任何東西 – DanielFitzgerald123 2012-04-11 10:45:20

0

您必須輸入RelativeLayout的ID,而不是xml fil名稱。 嘗試使用 RelativeLayout layout1 =(RelativeLayout)findViewById(R.id.yourRelativeLayoutViewID);

2

我想你會因爲沒有設置內容視圖而出現空白屏幕。 我的意思是代碼做它應該做的事情,然而,你應該刪除頂部的「setContentView()」方法並將其放在最後,然後在關閉onCreate之前將其設置爲RelativeLayout( ) 方法!就像這樣:

public void create() { 
RelativeLayout layout1 = new RelativeLayout(this); 
for(int i = 0; i < gridSize; i++) { 
    if(grid[i] == 0) { //if grid pos. indicates an empty cell 
     Button empty = new Button(this); 
     empty.setBackgroundResource(R.drawable.emptybutton); //set background to empty 
     empty.setId(i); //set id to value of i 
     empty.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
     layout1.addView(empty); //add the button to the relativeLayout view 
     //((Button) findViewById(i)).setOnClickListener(emptyListener); 
    } 
    } 
    setContentView(layout1); 
    } 

另外請注意,我已經改變了一點關於Relativelayout的聲明。 我希望這可以幫助。 :)!

+0

感謝您的答覆,我改變了桌面佈局,並增加了一些額外的代碼,現在它的工作 – DanielFitzgerald123 2012-04-27 09:44:42

+1

很高興我可以幫助 – Ange 2012-04-27 23:38:56

相關問題