这个问题与我之前发布的问题有关。 Views removed using removeView() are there when I next open the Activity (Android)
背景:当用户登录我的应用程序时,他们会从登录活动中转到主页活动。主页有一个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 :(得分:0)
这是我的不好,结果我每次用户登录时都会重新添加数据到sqlite数据库,而不会擦除以前的细节。
所以我的代码为数据库中的每个字段生成了一个按钮,应该是这样的。