0
0

More than 3 years have passed since last update.

とりあえずDarkModeに対応したい

Last updated at Posted at 2020-06-12

さっくりとやるのであれば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:バッテリーセーバー時に使用する

簡単ですね。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0