Is Android ViewParent a guarantee for a view group?

Is there any real case where View.getParent () returns an object that is not of type ViewGroup ? Or can I use it safely without checking its type first, as in my code example below?

  if (getParent() == null){ throw new IllegalStateException("View does not have a parent, it cannot be rootview!"); } ViewGroup parent = (ViewGroup) getParent(); 
+5
source share
3 answers

If you compare direct and indirect subclasses of ViewGroup and ViewParent, they look the same (taking into account the ViewGroup itself).

However, it is possible that in some user library you can get from getParent() a ViewParent , which is not a ViewGroup . Is this a real case?

So, if you cannot be sure of the parent type, you better check it out.
- in a regular application, you usually understand which parent or maybe - and therefore you can skip the check

+6
source

It is safe. Each implementation in the Android SDK for ViewParent is a ViewGroup .

But remember that instanceof also checks for invalidation. You can write:

 if (!(getParent() instanceof ViewGroup)){ throw new IllegalStateException("View does not have a parent, it cannot be rootview!"); } ViewGroup parent = (ViewGroup) getParent(); 
+3
source

If you do nothing, it should be safe. The only unsafe case is when you reach the root of your hiearchy look. Then ViewParent will be ViewRootImpl

+2
source

Source: https://habr.com/ru/post/1210331/


All Articles