我知道如何使用View.getRootView()来获取根视图。我也可以在button的onClick
事件中获取视图,其中参数是一个View。但是我该如何获取一个activity中的view呢?
我知道如何使用View.getRootView()来获取根视图。我也可以在button的onClick
事件中获取视图,其中参数是一个View。但是我该如何获取一个activity中的view呢?
如果你需要获取你的活动的根视图(这样你就可以在上面添加内容),请使用:
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。
以下是我用来获取根视图的代码,它对应于使用 setContentView
方法分配的 XML 文件中的视图:
final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
我只在 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@#######
请确认。在我们的活动中,我们可以使用以下代码获取root
视图:
ViewGroup rootView = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
或者View rootView = getWindow().getDecorView().getRootView();
在 Kotlin 中我们可以稍微简短一些:
val rootView = window.decorView.rootView
如果有人需要更简单的方式,请注意以下代码:
以下代码可查看整个活动:
View v1 = getWindow().getDecorView().getRootView();
要获取活动中特定的视图,例如活动内部的imageView,只需添加该视图的id即可:
View v1 = getWindow().getDecorView().getRootView().findViewById(R.id.imageView1);
希望这能对某人有所帮助
findViewById(R.id.imageView1);
。 - RobCo使用此方法可以简化在Activity中的访问。然后,您可以直接从Activity中引用rootView
,或者在Activity之外使用activity.rootView
:
val Activity.rootView get() = window.decorView.rootView
val Fragment.rootView get() = view?.rootView
View rootView = dataBinding.getRoot();
对于Kotlin用户来说,这甚至更简单:
val rootView = dataBinding.root
anyview.getRootView();
是最简单的方法。获取当前 Activity 的视图
在任何 onClick 中,我们都将获得 "View view",通过使用 'view' 获取 rootView。
View view = view.getRootView();
要在 Fragment 中获取视图
View view = FragmentClass.getView();
setContentView()
来指定要渲染的资源,并且您提供的视图已经是根视图。如果您需要该视图的处理句柄,只需在XAML中为其添加一个ID,然后使用findViewById()
即可。 - xandy