2011-02-13 55 views
0

我有一個活動需要對TableLayout進行各種條件更新(做/不顯示具有'0'值的行,創建新的行項目...等)。我有Dynamic TableLayout工作得非常好,但你可以想象這種排列繼續增長。我想將各種TableRow管理方法移到一個單獨的類中,但在轉換時遇到問題。將動態TableLayout方法移動到單獨的類

第一個問題是,當我嘗試從我的主要活動調用BuildTable.testTable();時,它希望方法是靜態的。這是有道理的,但是當我將testTable設置爲靜態時,那麼我得到的抱怨是「不能從類型Activity對靜態方法findViewById(int)進行靜態引用」。當我遵循here的建議時,似乎我非常接近解決方案,但它並沒有完全融合在一起。我需要幫助......並真誠地感謝你能提供的任何事情。

我已經熬下來的基礎之下,只有一個單一的TextView插入...我有:

public class BuildTable extends Activity { 

public void testTable() { 
    TableLayout tl = (TableLayout)findViewById(R.id.InvoiceTable); // Find TableLayout defined in main.xml 
     TableRow trDivider = new TableRow(getParent()); 
      TextView tvDivider = new TextView(getParent()); //Create a divider view between rows 
      tvDivider.setText("test"); 
     trDivider.addView(tvDivider); //Add tvDivider to the new row 
    tl.addView(trDivider); //Add trDivider to the TableLayout 
} 

回答

1

如果你真的想要一個static方法來做到這一點,只需將你的Activity傳入方法調用。

public class BuildTable { 

    private BuildTable(){ 
     // private as no need to create an instance 
    } 

    public static void testTable(Activity contextActivity) { 
     TableLayout tl = (TableLayout) contextActivity.findViewById(R.id.InvoiceTable); // Find TableLayout defined in main.xml 
     // etc 
    } 
} 

然後在您的Activity使用:

BuildTable.testTable(this); 
+0

我對這個社區的幫助感到震驚和謙卑。謝謝你們。我讀過的每一個答案都能起作用,並且他們都給了我指導我需要做出的改變。我選擇了這個答案,因爲它的工作如此之快,只需很少的努力。謝謝! – ctgScott 2011-02-13 19:38:07

1

的第一個問題是,當我試圖 呼叫BuildTable.testTable();從我 主要活動就是了方法 是靜態

你爲什麼要靜態調用這個函數?

如果您只是想分離某些功能,似乎沒有必要實際擴展活動。將它稱爲非靜態的,並使用對你的活動的引用可能是一件事情,就像這樣:(快速輸入,沒有通過編譯器運行它來查看我的語法混亂的位置:P)

public class BuildTable { //doesn't need activity 
private Activity contextActivity; //here is your activity 


public BuildTable(Activity yourContext){  //build a constructor 
    contextActivity = yourContext; 
} 

public void testTable() { 
    TableLayout tl = (TableLayout)contextActivity.findViewById(R.id.InvoiceTable); 
     TableRow trDivider = new TableRow(getParent()); 
      TextView tvDivider = new TextView(getParent()); 
      tvDivider.setText("test"); 
     trDivider.addView(tvDivider); //Add tvDivider to the new row 
    tl.addView(trDivider); //Add trDivider to the TableLayout 
} 
+0

你是對的...我真的不希望/需要它作爲靜態的。那恰好是在我有時用「糾正錯誤」的方法進行糾正時首先出現的錯誤。我要重建這個。 – ctgScott 2011-02-13 19:40:57

0

它要求該方法是靜態的,因爲您是通過它的類BuildTable.testTable()來調用它。如果你想創建一個BuildTbale類的實例,那麼它不一定是靜態的。

因此,在您的主要活動,你會說

BuildTable BT =新BuildTable(); bt.testTable(this); .....

然而,在你的情況下,我認爲你只需要創建一個方法不是一個新的類,除非你打算從多個活動或你調用它想要創建同一個類的多個實例。

+0

謝謝。你說得對,我不需要另外一堂課。我只是試圖做什麼看起來是家務。感謝您提供有關班級電話的提醒......這非常有幫助。 – ctgScott 2011-02-13 19:45:27