問題概述 (When)

在建立第一個 ComposeActivity 後,我想再建立一個 XML Layout 的 Activity,執行時就出現這個錯誤訊息。

This error message appear when I add second activity which using xml view after my first compose activity.

解決方法 (How to fix)

方法一

將 res/values/themes.xml 的程式碼從
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="Theme.Lab1230" parent="android:Theme.Material.Light.NoActionBar" />
</resources>

換成這樣 (這是我另開一個新專案,第 1 個 activity 是 View Activity 所自動產生的設定)

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="Theme.Lab1230" parent="Theme.Material3.DayNight.NoActionBar" />
</resources>

或是這樣也是可以 (這是我之前舊專案的設定)

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="Theme.Lab1230" parent="Theme.MaterialComponents.DayNight.NoActionBar" />
</resources>

方法二

直接為 SecondActivity 指定 theme 為 @style/Theme.AppCompat

但是這個方法會少了很多預設的值,例如:背景色…等。

如果是用來配合 CameraX ,這還 ok,但是如果是一般用途,採用方法一比較合適。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        ...
        <activity
            android:name=".SecondActivity"
            android:theme="@style/Theme.AppCompat"
            android:exported="false" />
        <activity
            android:name=".MainActivity"
            ...
        </activity>
    </application>

</manifest>

發生原因 (Why)

一般的 ViewActivity 需要 Theme.AppCompat 或其子類別的 theme 來配合,但是他找不到,因為專案的第 1 個 activity 是 Compose activity,他產生的的 theme,其 parent 是

如果專案的第 1 個 activity 是 View Activity,自動產生的 theme,其 parent 是 android:Theme.Material.Light.NoActionBar

Theme.Material3.DayNight.NoActionBar,這個 theme 不會有問題。

總結

如果專案還是會用到 view activity,第一個 activity 最好還是 view acitivity ,這樣會少很多麻煩。

疑問

這是 bug 嗎?官方有什麼解決的方法?

參考資料 (Reference)

Android – You need to use a Theme.AppCompat theme (or descendant) with this activity

Last modified: 2023 年 12 月 30 日

Author

Comments

Write a Reply or Comment

Your email address will not be published.