9

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 ?

akari
  • 617
  • 1
  • 11
  • 32

4 Answers4

11

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
Squonk
  • 48,735
  • 19
  • 103
  • 135
3

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

joao2fast4u
  • 6,868
  • 5
  • 28
  • 42
1

Surrounding imageview returns the parent layout id.

android:id="@+id/returnid"

example :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/returnid"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <iamageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="24dp"
        android:text="test"
        android:background="@drawable/white"
        />

</RelativeLayout>
Alaa
  • 539
  • 3
  • 8
  • 29
chakangost
  • 46
  • 2
1

When you have a parent view with no id, but you do have a child with an id, the best option is to use parent:

val layoutWithId: FrameLayout = findViewById(R.id.withWithId)
val noIdLayout: RelativeLayout = (layoutWithId as FrameLayout).parent as RelativeLayout

A proper tool here to identify the view tree is the Layout Inspector from AS menu: Tools > Layout Inspector

It will give you a better idea of how your views are display in the tree, then you can easily which one is parent of who

Carlos Daniel
  • 2,459
  • 25
  • 30