さっくりとやるのであればMatrialComponentを使うと便利です
build.gradle
dependencies {
...
implementation 'com.google.android.material:material:${version}'
}
ダークモード時に上書きしたいカラー定義を res/values-night/color.xml
に定義します。
res/values-night/color.xml
<resources>
<color name="override_color">#FFFFFF</color>
</resources>
MatrialComponentsのDayNightを継承したテーマを作成します
style.xml
<resources>
<style name="DarkThemeApp" parent="@style/Theme.MaterialComponents.DayNight.NoActionBar">
...
</style>
</resources>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.darktheme"
android:versionCode="1"
android:versionName="1.0">
<application
android:name=".DarkThemeApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/DarkThemeApp">
...
</application>
</manifest>
起動時に AppCompatDelegate.setDefaultNightMode
で設定してあげます
App.kt
public class DarkThemeApplication extends Application {
public void onCreate() {
super.onCreate();
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
}
- AppCompatDelegate.MODE_NIGHT_NO:どんなときでも使用しない
- AppCompatDelegate.MODE_NIGHT_YES:どんなときでも使用する
- AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM:システム設定に準拠する
- AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY:バッテリーセーバー時に使用する
簡単ですね。