Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an Android ViewParent guaranteed to be a Viewgroup?

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();
like image 455
Heisenberg Avatar asked Jan 03 '15 22:01

Heisenberg


2 Answers

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();
like image 75
pdegand59 Avatar answered Nov 16 '22 02:11

pdegand59


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

like image 42
mbonnin Avatar answered Nov 16 '22 03:11

mbonnin