Home » Android » Is an Android ViewParent guaranteed to be a Viewgroup?

Is an Android ViewParent guaranteed to be a Viewgroup?

Posted by: admin June 15, 2020 Leave a comment

Questions:

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();
How to&Answers:

If you compare direct and indirect subclasses of ViewGroup and ViewParent they look the same (considering ViewGroup itself).

Still it’s possible that in some custom library you may get from getParent() a ViewParent that isn’t ViewGroup. Is it a real case?

So
– if your can’t be sure of parent type you’d better check it.
– in ordinary app you usually understand what parent is or can be – and so you may skip check

Answer:

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();

Answer:

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