Quv
Quv

Reputation: 3149

Android: How to get the ID of a parent View?

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.

Upvotes: 14

Views: 24576

Answers (3)

Emrys90
Emrys90

Reputation: 1017

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

Upvotes: 3

aromero
aromero

Reputation: 25761

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.

Upvotes: 6

dmon
dmon

Reputation: 30168

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

Upvotes: 19

Related Questions