是的,Android AppCompatActivity 支持夜间模式。从 Android 10(API 级别 29)开始,Android 引入了一种名为夜间模式的系统级功能。要在您的 AppCompatActivity 中支持夜间模式,请按照以下步骤操作:
在 res 文件夹下创建一个名为 values-night 的新文件夹(如果尚未创建)。
在 values-night 文件夹中,创建一个名为 themes.xml 的新文件(如果尚未创建)。
在 themes.xml 文件中,定义一个继承自 Theme.AppCompat.DayNight 的主题。例如:
<resources> <style name="AppTheme.Night" parent="Theme.AppCompat.DayNight"> <!-- 自定义夜间模式下的样式 --> <item name="colorPrimary">@color/night_primary</item> <item name="colorPrimaryDark">@color/night_primary_dark</item> <item name="colorAccent">@color/night_accent</item> </style> </resources> AndroidManifest.xml 文件中,为 AppCompatActivity 设置 android:theme 属性,以使用您在步骤 3 中定义的夜间主题。例如:<activity android:name=".YourAppCompatActivity" android:theme="@style/AppTheme.Night"> <!-- 其他属性 --> </activity> res/values 文件夹中的 themes.xml 文件中定义一个默认主题,如下所示:<resources> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- 自定义默认样式 --> <item name="colorPrimary">@color/primary</item> <item name="colorPrimaryDark">@color/primary_dark</item> <item name="colorAccent">@color/accent</item> </style> </resources> 然后,在 AndroidManifest.xml 文件中的 <application> 标签中添加 android:theme 属性,以使用您在步骤 4 中定义的夜间主题:
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme.Night"> <!-- 其他属性 --> </application> 现在,您的 AppCompatActivity 应该在夜间模式下正常工作。请注意,您可能需要根据您的应用程序需求自定义样式。