无法使用View.rootView找到最顶层的视图

4
我在我的活动中有以下的视图结构:
  • 相对布局(id = 1)
    • 相对布局(id = 104)
      • 文本视图(id = 200)
现在,当触摸到文本视图时,我想要获取最顶层相对布局的id(即id = 1)。
我正在使用setOnTouchListener,并在其中编写两个日志语句,如下所示:
  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)
我能够使用第一个日志语句获取到最顶层相对布局的id(id = 1),但是第二个日志语句打印出-1。
请问有人可以解释一下为什么我无法使用View.rootView获取到最顶层相对布局吗?
供参考:View.rootView
1个回答

0
请通过以下代码检查您所获得的视图:
Log.d ("tally", "Inside text_view parent: " + (v.parent).toString())
Log.d ("tally", "Inside text_view parent.parent.id: " + (v. parent.parent).toString())

因为,我认为`v.rootView`给你的是视图层次结构中的最顶层视图。
【更新】
在我们之前的评论线程后,我在这里更新一下,如何跟踪,在调用`v.rootView`之后你得到了什么。
首先,阅读另一个链接以更好地理解Android的视图层次结构。 https://medium.com/@MrAndroid/android-window-basic-concepts-a11d6fcaaf3f#:~:text=DecorView%20is%20a%20ViewGroup%20so,event%20in%20the%20dispatchTouchEvent%20method
现在,让我们尝试以下事情:
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)
}

现在,使用下面的方法 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())
   }
 }

现在,检查 Log.d("tally","Inside text_view rootViewID: " +(v.rootView)。toString())。它给出了 RelativeLayout 还是其他类型? - Pravin Tadvi
抱歉,在上面的评论中放错了引用链接,请点击以下链接了解“decorview”是什么:https://akashsaggu-55383.medium.com/overlay-using-decorview-phonewindow-f13708710475 - Pravin Tadvi
请查看我对 track v.rootView 进行的更新答案,并理解在调用 View.rootView 后实际获得了什么。 - Pravin Tadvi
谢谢您提供的信息,对Android的视图层次结构有了很多清晰的认识。现在我想问的是,如果我在一个RelativeLayout(id = 1)中有一个TextView(id = 200),而这个RelativeLayout本身又在另一个RelativeLayout(id = 104)中,那么我能否直接使用TextView获取最顶层RelativeLayout(id = 1)的id,还是必须使用(textview.parent.parent as ViewGroup).id这样的方式?因为后面可能会有多个RelativeLayout嵌套,最后才是一个TextView,所以我想避免重复多次地使用textview.parent.parent.parent...来获取顶层RelativeLayout的id。 - Jatin guglani
我可以直接使用TextView获取我的最顶层相对布局(id = 1)的ID吗?是的,你可以使用我在更新答案中描述的trackParentView方法。为了得到你想要的结果,只需修改我的方法,将条件if(view.parent != relativeLayout)改为从该view获取id - Pravin Tadvi
显示剩余15条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接