{"id":602,"date":"2024-06-11T12:58:46","date_gmt":"2024-06-11T12:58:46","guid":{"rendered":"https:\/\/robotqa.com\/blog\/?p=602"},"modified":"2024-06-11T12:58:46","modified_gmt":"2024-06-11T12:58:46","slug":"creating-a-dynamic-ui-with-appcompat-daynight-theme-in-android","status":"publish","type":"post","link":"https:\/\/robotqa.com\/blog\/creating-a-dynamic-ui-with-appcompat-daynight-theme-in-android\/","title":{"rendered":"Creating a Dynamic UI with AppCompat DayNight Theme in Android"},"content":{"rendered":"<img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/blog.robotqa.com\/wp-content\/uploads\/2024\/06\/2024061109563124.png\" alt=\"daynight-theme-android\" width=\"512\" height=\"410\" class=\"aligncenter size-full wp-image-560\" srcset=\"https:\/\/blog.robotqa.com\/wp-content\/uploads\/2024\/06\/2024061109563124.png 512w, https:\/\/blog.robotqa.com\/wp-content\/uploads\/2024\/06\/2024061109563124-300x240.png 300w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/>\n<p><\/p>\nThe AppCompat DayNight theme is a part of the AndroidX library, enabling your app to automatically switch between light and dark themes based on the user&#8217;s device settings or preferences. This feature helps in creating a more dynamic and user-friendly UI, providing better readability in various lighting conditions. In this blog, we will walk through the steps to implement a simple Android UI using the AppCompat DayNight theme.\n<p><\/p>\n<h3><strong>Setting Up the AppCompat DayNight Theme<\/strong><\/h3>\nFirst, ensure you have the necessary dependencies in your <code>build.gradle<\/code> file.\n<p><\/p>\n<h4><strong>Step 1: Add Dependencies<\/strong><\/h4>\nOpen your <code>build.gradle<\/code> file and add the AndroidX AppCompat dependency:\n<pre class=\"lang:xhtml decode:true \">dependencies {\n    implementation 'androidx.appcompat:appcompat:1.3.1'\n    implementation 'androidx.core:core-ktx:1.6.0'\n}\n<\/pre>\n<p><\/p>\n<h4><strong>Step 2: Define the Theme in styles.xml<\/strong><\/h4>\nOpen your <code>res\/values\/styles.xml<\/code> file and define the AppCompat DayNight theme:\n<pre class=\"lang:xhtml decode:true \">&lt;resources&gt;\n    &lt;!-- Base application theme --&gt;\n    &lt;style name=\"AppTheme\" parent=\"Theme.AppCompat.DayNight.DarkActionBar\"&gt;\n        &lt;!-- Customize your theme here --&gt;\n        &lt;item name=\"colorPrimary\"&gt;@color\/purple_500&lt;\/item&gt;\n        &lt;item name=\"colorPrimaryDark\"&gt;@color\/purple_700&lt;\/item&gt;\n        &lt;item name=\"colorAccent\"&gt;@color\/teal_200&lt;\/item&gt;\n    &lt;\/style&gt;\n&lt;\/resources&gt;\n<\/pre>\nThis setup ensures that your application uses the DayNight theme with a dark action bar by default.\n<p><\/p>\n<h3><strong>Example: Creating a Simple UI with Toggle for DayNight Theme<\/strong><\/h3>\nLet\u2019s create a simple UI that includes a toggle button to switch between day and night modes manually.\n<p><\/p>\n<h4><strong>Step 3: Define the Layout<\/strong><\/h4>\nCreate an XML layout file (<code>activity_main.xml<\/code>) with the following content:\n<pre class=\"lang:xhtml decode:true \">&lt;LinearLayout\n    xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\n    android:padding=\"16dp\"\n    android:gravity=\"center\"&gt;\n\n    &lt;TextView\n        android:id=\"@+id\/greetingTextView\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"Hello, World!\"\n        android:textSize=\"24sp\"\n        android:layout_marginBottom=\"24dp\"\/&gt;\n\n    &lt;Button\n        android:id=\"@+id\/toggleThemeButton\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"Toggle Theme\"\/&gt;\n\n&lt;\/LinearLayout&gt;\n<\/pre>\n<p><\/p>\n<h4><strong>Step 4: Initialize in Activity<\/strong><\/h4>\nIn your <code>MainActivity.java<\/code> or <code>MainActivity.kt<\/code> file, initialize the views and add functionality to toggle the theme.\n\nJava\n<pre class=\"lang:java decode:true \">package com.example.daynighttheme;\n\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.appcompat.app.AppCompatDelegate;\n\npublic class MainActivity extends AppCompatActivity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        TextView greetingTextView = findViewById(R.id.greetingTextView);\n        Button toggleThemeButton = findViewById(R.id.toggleThemeButton);\n\n        \/\/ Load the saved theme preference\n        SharedPreferences sharedPreferences = getSharedPreferences(\"ThemePref\", MODE_PRIVATE);\n        boolean isNightMode = sharedPreferences.getBoolean(\"NightMode\", false);\n\n        if (isNightMode) {\n            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);\n        } else {\n            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);\n        }\n\n        toggleThemeButton.setOnClickListener(v -&gt; {\n            boolean nightMode = (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES);\n            if (nightMode) {\n                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);\n                saveThemePreference(false);\n            } else {\n                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);\n                saveThemePreference(true);\n            }\n        });\n    }\n\n    private void saveThemePreference(boolean isNightMode) {\n        SharedPreferences.Editor editor = getSharedPreferences(\"ThemePref\", MODE_PRIVATE).edit();\n        editor.putBoolean(\"NightMode\", isNightMode);\n        editor.apply();\n    }\n}\n<\/pre>\nKotlin\n<pre class=\"lang:kotlin decode:true \">package com.example.daynighttheme\n\nimport android.content.SharedPreferences\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.appcompat.app.AppCompatDelegate\n\nclass MainActivity : AppCompatActivity() {\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        setContentView(R.layout.activity_main)\n\n        val greetingTextView: TextView = findViewById(R.id.greetingTextView)\n        val toggleThemeButton: Button = findViewById(R.id.toggleThemeButton)\n\n        \/\/ Load the saved theme preference\n        val sharedPreferences: SharedPreferences = getSharedPreferences(\"ThemePref\", MODE_PRIVATE)\n        val isNightMode = sharedPreferences.getBoolean(\"NightMode\", false)\n\n        if (isNightMode) {\n            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)\n        } else {\n            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)\n        }\n\n        toggleThemeButton.setOnClickListener {\n            val nightMode = AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES\n            if (nightMode) {\n                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)\n                saveThemePreference(false)\n            } else {\n                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)\n                saveThemePreference(true)\n            }\n        }\n    }\n\n    private fun saveThemePreference(isNightMode: Boolean) {\n        val editor: SharedPreferences.Editor = getSharedPreferences(\"ThemePref\", MODE_PRIVATE).edit()\n        editor.putBoolean(\"NightMode\", isNightMode)\n        editor.apply()\n    }\n}\n<\/pre>\n<!-- CTA Section -->\n<p><\/p>\n<div class=\"bg-primary text-white text-center\">\n<div class=\"container space-1\"><span class=\"h6 d-block d-lg-inline-block font-weight-light mb-lg-0\"> <span class=\"font-weight-semi-bold\">Need Debugging?<\/span> \u2013 Try RobotQA and Start Debugging on Real Devices. <\/span> <a class=\"btn btn-sm btn-white transition-3d-hover font-weight-normal ml-3\" href=\"https:\/\/plugins.jetbrains.com\/plugin\/24460-robotqa-real-device-debugging-on-cloud\">Download Plugin<\/a><\/div>\n<\/div>\n<p><\/p>\n<!-- End CTA Section -->\n<h3><strong>Conclusion<\/strong><\/h3>\nUsing the AppCompat DayNight theme allows your app to dynamically adapt to the user\u2019s preferred theme, enhancing the user experience in different lighting conditions. By following this guide, you can easily implement the DayNight theme in your Android application and provide a toggle for users to switch between day and night modes manually. This approach ensures your app remains modern and user-friendly. Happy coding!","protected":false},"excerpt":{"rendered":"<p>The AppCompat DayNight theme is a part of the AndroidX library, enabling your app to automatically switch between light and dark themes based on the user&#8217;s device settings or preferences. This feature helps in creating a more dynamic and user-friendly&#8230;<\/p>\n","protected":false},"author":1,"featured_media":560,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[19],"tags":[39,40],"class_list":["post-602","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-app-debugging","tag-android-development","tag-android-themes"],"_links":{"self":[{"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/posts\/602","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/comments?post=602"}],"version-history":[{"count":0,"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/posts\/602\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/media\/560"}],"wp:attachment":[{"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/media?parent=602"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/categories?post=602"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/tags?post=602"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}