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


当前回答

从当前活动获取根视图。

在我们的活动中,我们可以通过以下方式获得根视图:

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

or

View rootView = getWindow().getDecorView().getRootView();

其他回答

以防有人需要更简单的方法:

下面的代码给出了整个活动的视图:

[View]

要在活动中获取某个视图,例如在活动中获取imageView,只需添加你想要获取的视图的id:

View v1 = getWindow().getDecorView().getRootView().findViewById(R.id.imageView1);

希望这对大家有所帮助

在Kotlin中,我们可以做得更短一些:

val rootView = window.decorView.rootView

我在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@#######

请证实。

从当前活动获取根视图。

在我们的活动中,我们可以通过以下方式获得根视图:

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

or

View rootView = getWindow().getDecorView().getRootView();

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

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