gpt4 book ai didi

android - findViewById(android.R.id.content) 是否可以为 Snackbars 返回 null?

转载 作者:太空狗 更新时间:2023-10-29 16:13:15 24 4
gpt4 key购买 nike

我希望能够显示 Snackbar,但我对必须为其提供 View 这一概念感到困惑。您可能认为它允许您默认在屏幕底部显示 Snackbar,但也许我遗漏了什么。

无论如何,这可以通过使用 View 来完成:

findViewById(android.R.id.content)

然而,我收到一条警告,指出这可能为 null,尽管无论我在哪里尝试它似乎总是有效。什么时候可能为空?

最佳答案

findViewById 如果您尝试查找当前布局中不存在的 View ,则始终可以为 null。

警告只是帮助。它可能非常通用,如果您查看 Activity 的源代码类,你会发现这个方法:

@Nullable
public View findViewById(@IdRes int id) {
return getWindow().findViewById(id);
}

Nullable 注释只是通知编译器这里可能会得到一个null 引用,Lint 会对此使用react。它不知道如何区分 findViewById(android.R.id.content) 或使用 findViewById(R.id.myCustomLayoutId) 的其他调用。不过,您或许可以自己添加 Lint 检查。

只要您在 Activity 中,就可以安全地使用 findViewById(android.R.id.content)

只要 onCreateView 被调用,您就可以在 Fragment 中安全地使用 getView()

关于android - findViewById(android.R.id.content) 是否可以为 Snackbars 返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37752087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com