3

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

4

2 回答 2

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;
    }

它至少返回视图本身。

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

你能把你的活动代码吗?

于 2013-04-26T22:36:06.287 回答
0

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

于 2013-04-27T18:16:33.917 回答