美文网首页
2019-04-02 onCreate方法不执行,白屏

2019-04-02 onCreate方法不执行,白屏

作者: HaloMartin | 来源:发表于2019-04-02 10:57 被阅读0次

有两个onCreate方法,略有不同

//1.这个是一般我们需要重写的
@Override
    protected void onCreate(Bundle savedInstanceState) {……}

//2.这个会导致异常
@Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

在 2. 中是我遇到的,我在重写onCreate方法时使用了两个参数的方法,导致出来效果Activity白屏,检查生命周期,只执行了onResume一次,查看Android API 27相关部分的源码,

    /**
     * Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
     * the attribute {@link android.R.attr#persistableMode} set to
     * <code>persistAcrossReboots</code>.
     *
     * @param savedInstanceState if the activity is being re-initialized after
     *     previously being shut down then this Bundle contains the data it most
     *     recently supplied in {@link #onSaveInstanceState}.
     *     <b><i>Note: Otherwise it is null.</i></b>
     * @param persistentState if the activity is being re-initialized after
     *     previously being shut down or powered off then this Bundle contains the data it most
     *     recently supplied to outPersistentState in {@link #onSaveInstanceState}.
     *     <b><i>Note: Otherwise it is null.</i></b>
     *
     * @see #onCreate(android.os.Bundle)
     * @see #onStart
     * @see #onSaveInstanceState
     * @see #onRestoreInstanceState
     * @see #onPostCreate
     */
    public void onCreate(@Nullable Bundle savedInstanceState,
            @Nullable PersistableBundle persistentState) {
        onCreate(savedInstanceState);
    }

可知,虽然最终调用的还是onCreate(savedInstanceState)但在一般的创建Activity的过程中该方法并不会被执行到,所以如果重写错误的话会导致界面没有被初始化完成,加上我们一般把UI加载都放在onCreate(savedInstanceState)中,所以导致界面白屏

原因比较简单,如果不知道有个这样的方法在,加上IDE有代码辅助输入的功能,还是会搞错的,重要的还是排错的方法要掌握。

相关文章

网友评论

      本文标题:2019-04-02 onCreate方法不执行,白屏

      本文链接:https://www.haomeiwen.com/subject/zwswbqtx.html