2013-05-09 83 views
0

理想情況下,可以通過findViewById方法檢索視圖引用(在xml文件中)。 但是我有我哪裏有實例化上面的代碼在一個特定的類定義的所有視圖如何檢索以編程方式定義的視圖引用

public View Initialise(Context context){ 

    private Button mBoardButtons[][] = new Button[gridSize][gridSize]; 
     private TableRow rowArr[] = new TableRow[gridSize]; 
     private TextView mInfoTextView; 
     private TextView mPlayer; 
     private TextView mPlayerCount; 
    TableLayout tableLayout1 = new TableLayout(context); 
     TableLayout.LayoutParams tableParams1 = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     tableParams1.topMargin = 0; 
     tableLayout1.setLayoutParams(tableParams1); 

     for (int i =0 ; i < gridSize ; i++){ 
      rowArr[i] = new TableRow(context); 
      TableRow.LayoutParams rowParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); 
      rowParams.gravity=Gravity.CENTER_HORIZONTAL; 
      rowArr[i].setLayoutParams(rowParams); 
      for(int j = 0; j < gridSize ; j++){ 
       mBoardButtons[i][j] = new Button(context); 
       mBoardButtons[i][j].setText(Integer.toString(i)+","+Integer.toString(j)); 
       mBoardButtons[i][j].setTextSize(150/gridSize); 
       mBoardButtons[i][j].setMaxHeight(450/gridSize); 
       mBoardButtons[i][j].setMaxWidth(600/gridSize); 
       rowArr[i].addView(mBoardButtons[i][j]); 

      } 
      tableLayout1.addView(rowArr[i]); 
     } 


     mInfoTextView = new TextView(context); 
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
       LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
      params.topMargin = 5; 
      params.gravity=Gravity.CENTER; 
     mInfoTextView.setLayoutParams(params); 
     mInfoTextView.setText("Info"); 
     mInfoTextView.setTextSize(25); 
     tableLayout1.addView(mInfoTextView); 


     TableLayout tableLayout2 = new TableLayout(context); 
     TableLayout.LayoutParams tableParams2 = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     tableLayout2.setLayoutParams(tableParams2); 

     TableRow tableRow = new TableRow(context); 

     mPlayer = new TextView(context); 

     mPlayer.setText("Player: "); 
     tableRow.addView(mPlayer); 

     mPlayerCount = new TextView(context); 

     mPlayerCount.setText(" "); 

     tableRow.addView(mPlayerCount); 


    return tableLayout1; 

} 

類(比方說,它的XML文件的替代品)

現在我該怎樣讓檢索引用爲我的Activity類中的所有這些視圖元素。

是否有任何方法類似於findViewById方法來檢索編程定義的視圖引用?

+0

爲什麼不將引用保留在與成員相同的類中,以便您可以在活動類中添加一些獲取器並訪問這些視圖 – damson 2013-05-09 18:25:55

回答

0

當你用新建立它們時你有參考。保存在某個地方。

或者您可以使用setID(),以便稍後使用findViewByID。但是,如果現在可以保存它,那麼這麼做很愚蠢。

+0

在xml文件中,我們膨脹或執行setContentView(R.layout.xmlfile) 我如何能夠引用編程定義的視圖元素? – 2013-05-09 18:28:51

+0

如果您正在以編程方式創建它們,那麼在創建它們時您就有了參考。只需保存它們以備後用。或者您可以在每個ID上調用setID,然後在該ID上使用findViewByID。 – 2013-05-09 18:33:56

相關問題