Reputation: 2380
I am creating a checkbox list with a button programmatically. For updating purpose I need to delete the old checkbox list and Button
before creating the new one in the remove_elements
method. How can I set their visibility
to GONE
in the remove_elements
method? With the current state any checkbox list and button is always being added without deleting the old one.
code in the 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() {
}
}
Upvotes: 0
Views: 77
Reputation: 512
As I recall the setVisibility
-method only changes the way the element is shown. View.GONE
means it won't take up any space in the layout but it will still be there.
To remove it completely you'll have to first get the parent layout which contains the elements, in your example I'm guessing it is the one with the id R.id.lila
, and then call 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");
}
}
There is also a removeAllViews()
-method you could use if the checkboxes are the only views in the LinearLayout
Upvotes: 1