排错:You need to use a Theme.AppCompat theme (or descendant) with this activity.

44 阅读1分钟

升级AndroidStuio后, 新建的项目模板是compose 模式的,因为我当前不需要compose模式,所以我就新建了一个EmptyActivity,但是运行时,会报错,You need to use a Theme.AppCompat theme (or descendant) with this activity.

class TestMainActivity : AppCompatActivity()

查看报错原因,代码在 class AppCompatDelegateImpl extends AppCompatDelegate 中,有如下报错

if (!a.hasValue(R.styleable.AppCompatTheme_windowActionBar)) {
    a.recycle();
    throw new IllegalStateException(
            "You need to use a Theme.AppCompat theme (or descendant) with this activity.");
}

查看hasValue 如下:

etermines whether there is an attribute at index.
Note: If the attribute was set to @empty or @undefined, this method returns false.

public boolean hasValue(@StyleableRes int index) {
    if (mRecycled) {
        throw new RuntimeException("Cannot make calls to a recycled instance!");
    }

    index *= STYLE_NUM_ENTRIES;
    final int[] data = mData;
    final int type = data[index + STYLE_TYPE];
    return type != TypedValue.TYPE_NULL;
}

意思就是找不到 这个theme, R.styleable.AppCompatTheme_windowActionBar 新建的 activity 不带theme, ,于是将新建的theme 配置为

android:theme="@style/Theme.AppCompat.Light.NoActionBar"

修改后,编译通过了。