View.getRoot()
returns View
, so we can easily figure out which is the root view by using getResourceName(View.getId())
.
View.getParent()
..., while I expect it also returns View
that is the parent, actually only returns an instance of ViewParent
that seems to have very very few useful method/fields. It sucks.
So, is there any way to know the ID of the parent? I believe a View
's parent is also View
, thus it should has mID field.
I really wonder why Google didn't let View.getParent()
just returns View
. It makes sense, only when something else other than View
could be the parent, and as far as I know, it's limited to View
and its subclasses.
ViewParent
is just an interface that any View that can have children implements. Most of the times the class you get back will be an instance of a ViewGroup
, like LinearLayout
or RelativeLayout
. I'm not exactly sure what you mean by "name" but if you want to get the class name you can do so like always: view.getParent().getClass().getName()
.
The docs state that the parent is not necessarily a View
:
public final ViewParent getParent ()
Added in API level 1 Gets the parent of this view. Note that the parent is a ViewParent and not necessarily a View.
Returns Parent of this view.
However all implementations of ViewParent
inherit from View
. This should be a design decision to decouple the parent from a View
using the ViewParent
interface, although all implementations in the SDK are views.
Try casting it first. For example, if the parent of the View that you're trying to get id of is a TableRow, then do
((TableRow)View.getParent()).getID()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.