2011-03-17 55 views
1

我正在使用從main擴展到設置某些按鈕的子類。我可以更改在main中創建的變量,例如子項內的TotalMoney。FindViewById在子類中使用時爲空

問題是findViewById給出了一個空指針異常。 buildthem()中的代碼在主類中使用時可以正常工作。

我正在使用setContentView(R.layout.main);從OnCreate中主要。 Child類實例化並從主類中的OnResume調用。

我是否需要在子節點中設置內容視圖,或者以某種方式傳遞主類中的內容視圖?

package com.chewyapps.markettrader; 

     class child extends main { 

    void buildthem(){ 

     TotalMoney = TotalMoney + 9999; 


      Button MenuButton = (Button) findViewById(R.id.Menu); 
      //etc 

    } 
} 

我可以在OnCreate中沒有findViewById因爲完整的代碼將使用

  for(i=0; i<buttonIDs.length; i++) {     
        Button b = (Button) findViewById(buttonIDs[i]); 
//do other stuff  
    } 

的對是需要與每個按鈕其他的事情循環。如果我能夠得到基本示例,但我認爲完整的代碼將起作用。

它沒有發生在我說這之前,但在子類是所謂的child.java一個單獨的文件,從我main.java文件中的onResume我用:

child childObject = new child(); 
    childObject.buildthem(); 

回答

1

爲什麼不把這個行:

Button MenuButton = (Button) findViewById(R.id.Menu); 
onCreate()

,那麼你可以通過MenuButtonbuildthem()作爲一個參數或直接引用它,這取決於你的設計。

請注意Java約定是變量名以小寫字母開頭,所以menuButton不是MenuButton

編輯
那麼,爲什麼不創造Button S IN onCreate()數組以後可以遍歷?

Button myButtons[] = new Button[buttonIDs.length]; 
for(int i=0; i<buttonIDs.length; i++) {     
    myButtons[i] = (Button) findViewById(buttonIDs[i]); 
} 

然後只是遍歷子類中的myButtons數組。

+1

關於命名約定好一點。 – trgraglia 2011-03-17 15:53:07

+0

請參閱編輯爲什麼我不能把它放在創造 – 2011-03-17 16:17:19

+0

@湯姆漢弗里斯更新了我的答案 – 2011-03-17 17:36:29

0

什麼:

Button MenuButton = (Button) this.findViewById(R.id.Menu); 

Button MenuButton = (Button) Child.this.findViewById(R.id.Menu); 
+0

嗯這些似乎沒有任何區別:( – 2011-03-17 16:17:50

+0

Meant:按鈕MenuButton =(按鈕)Parent.this.findViewById(R.id.Menu); – trgraglia 2011-03-17 16:26:00

+0

如果我嘗試日食顯示「沒有封閉的類型主實例可以在範圍內訪問「 – 2011-03-17 18:03:22

相關問題