此问题与我之前发布的问题有关。 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);
}
}