【问题标题】:findViewById(android.R.id.content).getRootView() nullPointerExceptionfindViewById(android.R.id.content).getRootView() nullPointerException
【发布时间】:2013-04-26 20:34:02
【问题描述】:

为什么在 onPause 或 onStop 中调用 findViewById(android.R.id.content).getRootView() 会返回 NPE,但在 onCreate 中调用时却没有?

【问题讨论】:

标签: android android-activity android-lifecycle rootview


【解决方案1】:

这里是android.view.View.getRootView()的代码:

public View getRootView() {
        if (mAttachInfo != null) {
            final View v = mAttachInfo.mRootView;
            if (v != null) {
                return v;
            }
        }

        View parent = this;

        while (parent.mParent != null && parent.mParent instanceof View) {
            parent = (View) parent.mParent;
        }

        return parent;
    }

它至少返回视图本身。

在我尝试在 onStoponPauseonCreateonResume 中记录 findViewById(android.R.id.content)findViewById(android.R.id.content).getRootView() 之后>,一切正常。没有 NPE。

你能输入你的活动代码吗?

【讨论】:

    【解决方案2】:

    我无法在 Android 4.2.2 上重现此错误。您可能会从其他地方得到那个 NullPointerException 。 顺便说一句,findViewById(android.R.id.content) 返回 rootview 所以getRootView() 通常是无效的。

    【讨论】:

      猜你喜欢
      • 2012-05-26
      • 2016-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-15
      • 2016-02-13
      • 1970-01-01
      相关资源
      最近更新 更多