解决报错This Activity already has an action bar supplied by the window decor.

在使用actionbar的时候可能会出现这样的报错
This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_ACTION_BAR and set android:windowActionBar to false in your theme to use a Toolbar instead.
刚开始看到这个报错会觉得比较奇怪,但是仔细分析一下就能发现问题的原因了
首先在源码中(使用Android xref)找到报异常的位置,最后在activity.java找到如下代码

public void setActionBar(@Nullable Toolbar toolbar) {
        final ActionBar ab = getActionBar();
        if (ab instanceof WindowDecorActionBar) {
            throw new IllegalStateException("This Activity already has an action bar supplied " +
                    "by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " +
                    "android:windowActionBar to false in your theme to use a Toolbar instead.");
        }

        // If we reach here then we're setting a new action bar
        // First clear out the MenuInflater to make sure that it is valid for the new Action Bar
        mMenuInflater = null;

        // If we have an action bar currently, destroy it
        if (ab != null) {
            ab.onDestroy();
        }

        if (toolbar != null) {
            final ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this);
            mActionBar = tbab;
            mWindow.setCallback(tbab.getWrappedWindowCallback());
        } else {
            mActionBar = null;
            // Re-set the original window callback since we may have already set a Toolbar wrapper
            mWindow.setCallback(this);
        }

        invalidateOptionsMenu();
    }

能够走到这段代码,说明应用是使用toolbar来代替actionbar的
首先会获取当前的actionbar对象ab,如果已经设置toolbar,则类型为Toolbar,否则为默认的WindowDecorActionBar,然后进行类型判断
如果ab的类型为WindowDecorActionBar,表明已经设置过默认actionbar了,将WindowDecorActionBar替换成Toolbar是不被允许的,所以抛出异常

出现这种情况一般可能由以下几种原因

  • 当前theme的parent含有属性<item name="android:windowActionBar">true</item>
  • 当前activity的父类可能执行了对actionbar的操作,例如getActionBar,setDisplayHomeAsUpEnabled
    知道问题的原因后,解决也就很容易了
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容