【问题标题】:Can findViewById(android.R.id.content) ever return null for Snackbars?findViewById(android.R.id.content) 可以为 Snackbars 返回 null 吗?
【发布时间】:2016-10-11 15:34:12
【问题描述】:

我希望能够显示 Snackbars,但我对必须为其提供视图的想法感到困惑。您可能会认为默认情况下它允许您在屏幕底部显示 Snackbar,但也许我遗漏了一些东西。

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

findViewById(android.R.id.content)

但是我得到一个警告,这可能是空的,即使它似乎总是在我尝试它的地方工作。什么时候可能为空?

【问题讨论】:

标签: android findviewbyid snackbar


【解决方案1】:

如果您不在 AppCompatActivity 中,则通过活动

public static void snackBar(Activity activity, String MESSAGE) {
    Snackbar.make(activity.findViewById(android.R.id.content), MESSAGE, Snackbar.LENGTH_LONG).show();
}

如果你有上下文,你可以这样尝试

public static void snackBar(Context context, String MESSAGE) {
    Snackbar.make(((Activity)context).findViewById(android.R.id.content), MESSAGE, Snackbar.LENGTH_LONG).show();
}

【讨论】:

    【解决方案2】:

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

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

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

    Nullable 注释只是通知编译器可能会在此处获得null 引用,Lint 会对此做出反应。它不知道如何区分findViewById(android.R.id.content) 或其他带有findViewById(R.id.myCustomLayoutId) 的呼叫。不过,您可以自己添加 Lint 检查。

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

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

    【讨论】:

    • 当您在 Fragment 中但希望 Snackbar 显示在整个屏幕的底部时会怎样? getActivity().findViewById(android.R.id.content) 什么的?
    • 嗯,是的,您可以致电getActivity().findViewById(android.R.id.content) 获取根视图。
    • 它还告诉我 getView() 可能为空——同样的想法?可能为空,但可能不是?
    • getView()也被@Nullable注解,所以也可以返回null。如果您在调用 onViewCreated 之前调用它,它将返回 null。
    猜你喜欢
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多