我知道如何使用view . getrootview()获得根视图。我也能够从一个按钮的onClick事件中获得视图,其中参数是一个视图。但是我如何在活动中获得视图呢?


当前回答

对于那些正在使用数据绑定库的人来说,要获得当前活动的根,只需使用:

View rootView = dataBinding.getRoot();

对于Kotlin用户来说,它甚至更简单:

val rootView = dataBinding.root

其他回答

如果你需要根视图你的活动(所以你可以添加你的内容)使用

findViewById(android.R.id.content).getRootView()

此外,据报道,在某些设备上,你必须使用

getWindow().getDecorView().findViewById(android.R.id.content)

代替。

请注意,正如Booger所报告的,这可能在某些设备上位于导航栏后面(带有返回按钮等)(但在大多数设备上似乎不是这样)。

如果你需要使用setContentView()方法获取你添加到你的活动的视图,然后作为pottedmeat写你可以使用

final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
            .findViewById(android.R.id.content)).getChildAt(0);

但最好在xml布局中设置id为这个视图,并使用这个id。

这是我用来获得根视图,因为在XML文件中找到了setContentView赋值:

final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
            .findViewById(android.R.id.content)).getChildAt(0);

获取当前活动的视图

在任何onClick我们将得到“视图视图”,通过使用“视图”得到rootView。

View View = View . getrootview ();

并在片段中获取View

View view = FragmentClass.getView();

我在android 4.0.3中测试了这个功能,只有:

getWindow().getDecorView().getRootView()

给我们同样的观点

anyview.getRootView();

com.android.internal.policy.impl.PhoneWindow$DecorView@#########

and

getWindow().getDecorView().findViewById(android.R.id.content)

给它的孩子

android.widget.FrameLayout@#######

请证实。

对于那些正在使用数据绑定库的人来说,要获得当前活动的根,只需使用:

View rootView = dataBinding.getRoot();

对于Kotlin用户来说,它甚至更简单:

val rootView = dataBinding.root