在Android中没有简单,通用的方式来获得的布局根视图?视图、布局、简单、方式

2023-09-05 07:06:28 作者:或许我早该放弃了ゝ

我不知道是否有一个通用的方法,在Android Activity类,让你得到该活动的布局根视图。我知道我能做到这样:

I'm wondering if there is a general-purpose method in the Android Activity class to allow you to get the root View of that Activity's layout. I know I can do it this way:

View v = findViewById(R.id.root_view_id)

不过,我想是能够做到这一点,而无需通过在根视图的ID。我必须这样做了很多不同的活动,这将是方便多了,如果我有一个尺寸适合所有人的方法调用来完成这项任务。

But I would like to be able to do it without having to pass in the ID of the root view. I need to do this for a lot of different Activities, and it would be a lot more convenient if I had a one-size-fits-all method call to accomplish the task.

推荐答案

这answer和评论给一个方法:

findViewById(android.R.id.content)

由于层次结构中的任何视图中,您也可以拨打:

Given any view in your hierarchy you can also call:

view.getRootView()

要获得该层次结构的根视图。

to obtain the root view of that hierarchy.

在装修意见还可以通过 getWindow获得()。getDecorView()。这是视图层次结构以及它附加到窗口点的根目录,但我不知道你想与之直接搞乱。​​

The "decor view" can also be obtained via getWindow().getDecorView(). This is the root of the view hierarchy and the point where it attaches to the window, but I'm not sure you want to be messing with it directly.