Is there any real case where View.getParent
() returns an object that is not of type ViewGroup
? Or can I safely cast it without checking its type first like in my code sample below ?
if (getParent() == null){
throw new IllegalStateException("View does not have a parent, it cannot be rootview!");
}
ViewGroup parent = (ViewGroup) getParent();
It's safe. Every single implementation, in the Android SDK, of ViewParent
is a ViewGroup
.
But remember that instanceof
also checks for nullity. You could write :
if (!(getParent() instanceof ViewGroup)){
throw new IllegalStateException("View does not have a parent, it cannot be rootview!");
}
ViewGroup parent = (ViewGroup) getParent();
If you aren't doing anything fancy, it should be safe. The only unsafe case is when you reach the root of your view hiearchy. The ViewParent will then be a ViewRootImpl
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With