有没有可靠的方法可以在不使用findViewById的情况下获取setContentView设置的ViewGroup?

发布于 2025-01-14 23:27:30 字数 489 浏览 1 评论 0原文

我创建了一个 Android 库,其中它接收一个 Activity 对象作为初始化的输入,在我的库初始化期间,我想获取由 Activity.setContentView 设置的 ViewGroup,我尝试过这种方式:

public void init(Activity activity) {
    ViewGroup tmp = activity.findViewById(android.R.id.content);
    ViewGroup currentVG = (ViewGroup) tmp.getChildAt(0);
}

它有效,但我不没有找到任何官方文档来证实这一点,我怀疑它可能适用于我的设备或某些特定的 Android 版本,但不适用于其他版本,无论如何我不确定。

  • 有这方面的官方文档吗?
  • 使用上面的方式在不使用 findViewById 的情况下检索 ViewGroup 是否安全?如果不行的话有什么靠谱的办法吗?

I create an Android Library in which it receives an Activity object as an input for initializing, during the initialization of my library, I want to get the ViewGroup set by Activity.setContentView, I've tried this way:

public void init(Activity activity) {
    ViewGroup tmp = activity.findViewById(android.R.id.content);
    ViewGroup currentVG = (ViewGroup) tmp.getChildAt(0);
}

It works, but I don't find any official documentation to confirm that, I suspect that It may work on my device or some specific Android version, but not for others, anyway I'm not sure.

  • Is there any official documentation for that?
  • Is it safe to use the way above to retrieve the ViewGroup without using findViewById? If not, Is there any reliable way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

牵强ㄟ 2025-01-21 23:27:30

当您调用 setContentView 时,Android 使用 LayoutInflater 来膨胀资源并为您的 Activity 构建视图层次结构。所以使用findViewById来获取视图的根就可以了。不确定为什么要在内容视图上调用 getChildAt(0) 。如果您想要内容视图的根,可以调用 View#getRootView< /a>

您可能需要添加一些错误处理,以防 Activity 被销毁或从未初始化(视图无效,findViewById 将返回 null。)

您还需要小心,不要保留对 Activity 的任何引用,或任何其他 UI 生命周期对象,以避免潜在的资源泄漏。

When you call setContentView Android uses a LayoutInflater to inflate the resource and build the hierarchy of views for your Activity. So it's fine to use findViewById to get the root of the view. Not sure why you are calling getChildAt(0) on the content view. If you want the root of the content view you can call View#getRootView

You might want to add some error-handling in case the Activity was destroyed or never initialized (views are not valid and findViewById will return null.)

You'll also want to be careful not to hang on to any references to activities, or any other UI lifecycle objects, to avoid potential resource leaks.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文