Этот вопрос относится к одному, который я опубликовал ранее. Views removed using removeView() are there when I next open the Activity (Android)getChildCount() возвращает 0 при вызове TableLayout
Справочная информация. Когда пользователь входит в мое приложение, они берутся из активности входа в главную страницу. На главной странице есть 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);
}
}