Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android get layout parent id

I would like to know what is the difference between View and ViewParent ? I am trying to get the Id of the parent of an ImageView but this I can't do :

myImageView.getParent().getId();

So is there another way to get this id ?

like image 534
akari Avatar asked Mar 31 '14 10:03

akari


2 Answers

I would like to know what is the difference between View and ViewParent ?

A View is a class and a ViewParent is an interface.

Although many of the common layout classes implement the ViewParent interface it isn't guaranteed.

The problem you're having is that the myImageView.getParent() is returning a ViewParent which doesn't directly expose a getId() method.

As others have said, casting the ViewParent to a View using...

((View) myImageView.getParent()).getId();

...should work at compile time but be aware of the following...

  1. If the parent View doesn't implement the ViewParent interface then the cast will fail.
  2. The parent View must have a resource id defined in the layout file as (for example) android:id=@+id/myParentViewId or the call to getId will return null
like image 78
Squonk Avatar answered Oct 01 '22 10:10

Squonk


You have to cast your parent view to a View, so you can use getId() method, using ((View) myImageView.getParent()).getId()

like image 36
joao2fast4u Avatar answered Oct 01 '22 10:10

joao2fast4u