user2436032
user2436032

Reputation: 365

How can we destroy the View from inside the view?

I have a Custom View which has a button clicking on which would destroy the Custom View. I want the logic of the destruction inside the View only so that I can dynamically add the View anywhere without writing the its destruction code in its parent. So I came up with the following code

  this.removeAllViews();
  ((ViewGroup) this.getParent()).removeView(this);

Is this the correct way, or is there some more elegent way of destroying the view ?

Upvotes: 2

Views: 3721

Answers (2)

natario
natario

Reputation: 25194

Looks legit to me. That's the point where I would release resources also.

To be sure the layout is still around, I would also check for nullity on getParent():

this.removeAllViews();
if (this.getParent() != null) {
    ((ViewGroup) this.getParent()).removeView(this);
}

Of course you should not hold references to this view inside other classes, say Activity of Fragment, because then view might get destroyed or, worse, just removed from the layout, without you even knowing.

If you really need some reference to your RemovableView inside other classes then you should implement some sort of interface as per the other answer. But in my opinion the code could stay the same, inside the custom view:

public class RemovableView {

    private void remove() {

        this.removeAllViews();
        if (this.getParent() != null) {
            ((ViewGroup) this.getParent()).removeView(this);
        }

        activity.onViewRemoved();
    }
}

and then

public class Activity implements MyCallback {

    private RemovableView view; 

    @Override
    public void onViewRemoved() {
        //do what you need to do, if any.
        }
}

This could fit your needs, as destroy code stays inside the view class, and you only implement the interface if you really need to. I believe there's no need to call viewGroup.removeView(view) from the Activity, since it is the exact same method called on the same object.

Upvotes: 3

Marcin Orlowski
Marcin Orlowski

Reputation: 75646

I want the logic of the destruction inside the View

This is wrong approach if you ask me. View/Fragment is just part of bigger picture managed by either i.e. parent Activity or parent Fragment etc and usually got no idea about other elements or relationships. So if element needs to be gone, it should tell its parent to be removed therefore your parent/host should expose interface your child should use to ask for the removal.

Upvotes: 0

Related Questions