Unable to Find the topmost view using View.rootView

73 views Asked by At

I have the following View structure in my activity:

  • Relative Layout (id = 1)
    • Relative Layout (id = 104)
      • TextView (id = 200)

Now when TextView is touched, I want to get the topmost relative layout's id (i.e. id = 1)

I'm using setOnTouchListener and inside that, I'm writing two log statements as follows:

  1. Log.d ("demo", "Inside text_view parent.parent.id: " + (v.parent.parent as ViewGroup).id)
  2. Log.d ("demo", "Inside text_view rootViewID: " + (v.rootView as ViewGroup).id)

I'm able to get my topmost relative layout's id (id = 1) using 1st log statement but the second log statement is printing -1.

could someone please explain why I'm not able to get the topmost relative layout using View.rootView?

for reference: View.rootView

1

There are 1 answers

8
Pravin Tadvi On BEST ANSWER

Please check what view you have got exactly by below code:

Log.d ("tally", "Inside text_view parent: " + (v.parent).toString())
Log.d ("tally", "Inside text_view parent.parent.id: " + (v. parent.parent).toString())

Because, I think, v.rootView give you topmost view of view hierarchy .

[UPDATE]

After our threads of Comment, I update here, how to track, what is exactly you got after calling v.rootView

first, read another link to better understand android's view hierarchy

https://medium.com/@MrAndroid/android-window-basic-concepts-a11d6fcaaf3f#:~:text=DecorView%20is%20a%20ViewGroup%20so,event%20in%20the%20dispatchTouchEvent%20method.

Now, let's try below things:

Log.d ("demo", "Inside text_view parent: " + (v.parent).toString())
Log.d ("demo", "Inside text_view parent.parent.id: " + (v.parent.parent).toString())

Log.d ("demo", "Inside text_view getRootView: " + (v.getRootView()).toString())
Log.d ("demo", "Inside text_view getRootView Name: " + (v.getRootView().accessibilityClassName).toString())
Log.d ("demo", "Inside text_view getRootView is ViewGroup: " + (v.getRootView() is ViewGroup))

if(v.getRootView() is ViewGroup){
  var vg: ViewGroup  = v.getRootView() as ViewGroup;
  trackParentView(v,0, vg)
}

Now, use below method trackParentView(...):

fun trackParentView(view :View, cnt :Int, rootView :ViewGroup){
   //Log.d ("trackParentView()", "view (name) [track: "+cnt+"]: "+ view.accessibilityClassName)
   Log.d ("trackParentView()", "view (toString) [track: "+cnt+"]: "+ view.toString())
   if(view.parent != rootView){
     trackParentView(view.parent as View, cnt+1, rootView)
   } else {
     Log.d ("trackParentView()", "this is rootView at : ["+cnt+"]: "+ view.toString())
   }
 }