2014-09-26 67 views
0

此問題與我之前發佈的問題有關。 Views removed using removeView() are there when I next open the Activity (Android)getChildCount()在TableLayout上調用時返回0

背景:當用戶登錄到我的應用程序中時,它們將從登錄活動中移至主頁面活動。主頁有一個包含動態生成按鈕的TableLayout。但是,如果用戶註銷並重新登錄,所有這些按鈕都會重複出現,因此我試圖找出如何在生成這些按鈕後最好地移除這些按鈕。在我之前的文章中,有人建議我在主頁面活動開始時刪除按鈕,然後再繪製新的按鈕,所以這就是我想要實現的。

但是,當我在此佈局上調用getChildCount()時,它並不總是返回正確的答案。

到目前爲止,這裏是在主頁活動開始運行代碼:

 TableLayout tableLayout = (TableLayout)findViewById(R.id.MainPageTableTitle); 
     //removeSectionButtons(tableLayout); this is where i am trying to remove the buttons 
     System.out.println("there are oncreate " + tableLayout.getChildCount()); 
     drawButtons(tableLayout); 
     System.out.println("there are ondraw " + tableLayout.getChildCount()); 

打印的第一行返回0,第二個打印行總是返回正確答案(按鈕的數量包括所有重複的)。但我不確定爲什麼getChildCount()第一次返回錯誤的答案。如果任何人都可以解釋我是令人難以置信的感激

我drawButtons()方法如下(它吸引每行有兩個按鈕):

 public void drawButtons(TableLayout tableLayout){ 
    //get the number of buttons 
    int noOfButtons = mySectionTableHandler.getSectionDetails().size(); 
    //calculate the number of rows needed (there are 2 columns) 
    //set flag to say if buttons are odd as it affects how many are drawn 
    int noOfRows; 
    boolean evenNoOfButtons; 
    if(noOfButtons % 2 == 0){ 
     //even no of buttons 
     noOfRows = noOfButtons/2; 
     evenNoOfButtons = true; 
    } else { 
     //odd no of buttons 
     noOfRows = (noOfButtons+1)/2; 
     evenNoOfButtons = false; 
    } 

    //counter to give each button a unique id 
    int counter = 1; 

    for(int i = 0; i<noOfRows;i++){ 
     TableRow newRow = new TableRow(this); 

     Button a = new Button(MainPageActivity.this); 
     a.setId(counter); 
     sectionButtons.put(counter, a); 
     counter++; 
     newRow.addView(a); 

     //if there are even buttons OR if there are an odd no 
     //of buttons but this isn't the last row then add 
     //second button to row 
     if(evenNoOfButtons || (!evenNoOfButtons && (noOfRows-1!=i))){ 
      Button b = new Button(MainPageActivity.this); 
      b.setId(counter); 
      sectionButtons.put(counter, b); 
      counter++; 
      newRow.addView(b); 
     }  
     tableLayout.addView(newRow); 
    } 

} 

回答

0

這是我不好,原來我重新添加數據每次用戶登錄到sqlite數據庫而不刪除以前的細節。

所以我的代碼是爲數據庫中的每個字段生成一個按鈕,因爲它應該是。

相關問題