从当前活动获取根视图

妖精的绣舞 提交于 2020-02-05 05:23:27

我知道如何使用View.getRootView()获得根视图。 我还可以从按钮的onClick事件获取视图,其中参数为View 。 但是如何获得活动中视图


#1楼

我只在android 4.0.3中测试过:

getWindow().getDecorView().getRootView()

给出相同的看法

anyview.getRootView();

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

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

给它的孩子

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

请确认。


#2楼

万一有人需要更简单的方法:

以下代码提供了整个活动的视图:

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

要在活动中获取证书视图,例如活动中的imageView,只需添加要获取的视图的ID:

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

希望这对某人有帮助


#3楼

如果您处于活动中,则假定只有一个根视图,您可以像这样获得它。

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

然后可以将其投放到您的真实班级

或者你可以使用

getWindow().getDecorView();

请注意,这将包括操作栏视图,您的视图位于操作栏视图下方


#4楼

从当前活动获取根视图。

在我们的活动中,我们可以获得以下内容的root视图:

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

要么

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

#5楼

如果您需要活动的根视图(以便可以在其中添加内容),请使用

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。


#6楼

获取当前活动的视图

在任何onClick中,我们都将使用“视图”获得rootView,从而获得“视图视图”。

视图view = view.getRootView();

并获得片段视图

视图view = FragmentClass.getView();


#7楼

anyview.getRootView(); 将是最简单的方法。


#8楼

这就是我用来获取在setContentView分配的XML文件中找到的根视图的方法:

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

#9楼

在Kotlin中,我们可以缩短操作时间:

val rootView = window.decorView.rootView
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!