業界トップクラスの求人数を誇る転職エージェントPR

リクルートグループのコネクションを活かした非公開求人も充実、他にはない好条件の求人と出会える

9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DarkTheme対応

Posted at

はじめに

Android10よりDarkThemeを適用することで、バッテリーの消費を抑えるなどの効果が得られるようになりました。
本稿ではDarkThemeへの対応方法を説明します。

DarkTheme対応

DarkTheme対応方法を下記に示します。

style

styles.xml
<!--AppCompat-->
<style name="AppTheme" parent="Theme.AppCompat.DayNight">

<!--MaterialComponent-->
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">

AppCompatのスタイルを使う時はres/values/styles.xmlにDayNightテーマを記述して使います。
また、MaterialComponentのスタイルを使うこともできます(com.google.android.material:material:1.1.0-alpha1から)

以上でシステムの設定によりDarkまたはLightのスタイルがアプリに適用されます。

強制的にDarkThemeを設定する

sample.kt
//DarkTheme適用
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)

//LightTheme適用
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)



AppCompatDelegate.setDefaultNightMode()を呼ぶことで意図的にThemeを設定することができます。
また、この設定を変えたイベントはconfigChangesで受け取ることができます。

AndroidManifest.xml
<activity
  android:name=".MyActivity"
  android:configChanges="uiMode" />
sampleActivity.kt
override fun onConfigurationChanged(newConfig: Configuration) {
  super.onConfigurationChanged(newConfig)
  //現在のThemeを取得
  val currentNightMode = configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
  when (currentNightMode) {
    Configuration.UI_MODE_NIGHT_NO -> {
      //LightThemeの場合
    }
    Configuration.UI_MODE_NIGHT_YES -> {
      //DarkThemeの場合
    }
  }
}

resourceフォルダの使いわけ

通常とは別にDarkTheme用のリソースを定義したい場合はvresフォルダにalues-nightのように-nightを付けた名前のフォルダを定義して、リソースを設定しておくことでDarkThemeが適用された時にそのリソースが使われます。

参考

Android Developers

9
6
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?