2015-06-01 2 views
0

Я создаю список флажков с помощью кнопки программно. Для целей обновления мне нужно удалить старый список флажков и Button перед созданием нового в методе remove_elements. Как установить visibility на GONE в методе remove_elements? В текущем состоянии все флажки и кнопка всегда добавляются без удаления старого.Установите видимость на GONE

код в MainActivity:

ArrayList<Integer> items = new ArrayList<Integer>(); 
    LinearLayout ll; 
    . 
    . 
    . 
    . 
    @Override 
    public void onAsyncTaskFinished(ArrayList<Integer> result) { 

     remove_elements(); 
     createCheckboxList(result); 


    } 

     private void remove_elements() { 
     for (int i : items) { 
      CheckBox ch = (CheckBox) findViewById(i); 
      if (ch != null) { 
       ch.setVisibility(View.GONE); 
      } else { 
       System.out.println("The checkbox is null"); 
      } 

     } 

     Button btn = (Button) findViewById(1); 
     if (btn != null) { 
      btn.setVisibility(View.GONE); 
     } else { 
      System.out.println("The button is null"); 
     } 

    } 
    private void createCheckboxList(final ArrayList<Integer> items) { 
     this.items = items; 
     final ArrayList<Integer> selected = new ArrayList<Integer>(); 

     ll = (LinearLayout) findViewById(R.id.lila); 
     for (int i = 0; i < items.size(); i++) { 
      CheckBox cb = new CheckBox(this); 
      cb.setText(String.valueOf(items.get(i))); 
      cb.setId(items.get(i)); 
      ll.addView(cb); 

     } 
     Button btn = new Button(this); 
     btn.setLayoutParams(new LinearLayout.LayoutParams(500, 150)); 
     btn.setText("submit"); 
     btn.setId(1); 
     ll.addView(btn); 

     btn.setOnClickListener(new View.OnClickListener() { 
    } 
} 

ответ

1

Насколько я помню setVisibility -метод только изменяет способ показан элемент. View.GONE означает, что он не займет места в макете, но он все равно будет там.

Чтобы удалить его полностью, вам нужно сначала получить родительский макет, содержащий элементы, в вашем примере я предполагаю, что он имеет идентификатор R.id.lila, а затем вызывает removeView.

private void remove_elements() { 
    LinearLayout parent = (LinearLayout) findViewById(R.id.lila); 
    for (int i : items) { 
     CheckBox ch = (CheckBox) findViewById(i); 
     if (ch != null) { 
      parent.removeView(ch); 
     } else { 
      System.out.println("The checkbox is null"); 
     } 
    } 

Существует также removeAllViews() -метод вы могли бы использовать, если галочки являются единственным мнением в LinearLayout