Exploring the Android theme Switch day and night mode _android

Source: Internet
Author: User

The rapid popularization of smartphones has greatly enriched our entertainment life. Now everyone likes to go to bed at night before the mobile phone, but the application of daytime mode is often too bright, the eyes have more serious damage. As a result, today's applications tend to develop both daytime and night modes for user Switching, and how do daytime and night mode switching actually happen?

In the type of app, it basically involves night mode, is to be able to according to different settings, presenting different styles of the interface to users, and at night do not hurt the eyes, the realization of the way is the so-called skin (theme switching), for the implementation of the night mode on the internet spread a lot of ways, here first to share a method for everyone , and reduce the brightness and chroma of the screen by setting the background as a transparent method.

Night Mode Code

public void Night () {
  windowmanager.layoutparams params = new Windowmanager.layoutparams (
      Layoutparams.match_ PARENT, Layoutparams.match_parent,
      WindowManager.LayoutParams.FLAG_NOT_ Touchable
          | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
  if (myview==null) {
    myview=new TextView (this);
    Myview.setbackgroundcolor (0x80000000);
  Mwindowmanager.addview (MyView, params);
  Editor edit = Skinsp.edit ();
  Edit.putstring ("Skin", NIGHT);
  Edit.commit ();

Daytime mode

public void Day () {
  if (myview!=null) {
    mwindowmanager.removeview (myview);
    Editor edit = Skinsp.edit ();
    Edit.putstring ("Skin", day);
    Edit.commit ();

Here's an example to detail how to do the day/night mode in the android theme switch.

The above two pictures, it is two app of the night mode effect, so, according to this function, to see how to switch the theme is how to achieve (of course, now GitHub have many plugintheme open source plug-ins, many times can use these plug-ins, but I do not want to talk about how to use those plug-ins, It would be better to use wheels than to build wheels.

About changing themes and changing skins

This refers to the function of changing the theme, of course, is similar to the skin change, skin change is now more popular is the use of plug-in dynamic loading technology to achieve, so that can play a hot plug function, the need for the skin when the user's own online download is, without the skin will delete the skin plug-in package and will not affect the Host app function, So you don't have to put a lot of skin pictures on the local and increase the size of the APK, about the use of plug-ins to achieve the skin function this is only the tip of the plug-in technology, on the plug-in technology more role, you can see 360 before two days of open source Droidplugin plug-in framework, Openaltas framework, There is also the Chairman's DL framework.

Well, now we need to realize is the theme of the switch, the theme switch is actually switching the entire app color style, layout style, font style, and so on, which will not have too much of the picture resources to switch, if there are too many pictures of the replacement that is the function of skin change.
Now we want to implement the night/day mode switching function, the following effect chart:

You can see the effect of the above is the night and day of the two modes of switching function, switch to night mode, the entire app's background color, font color, button color, title bar color, and so on all need to cut into the color of the night mode, when the cut back to the day mode and cut back the original color, to see how to do?

Implementing Theme Switching

The first is the need to prepare two sets of topics in the app:

Daytime theme

<resources> <style name= "Daytheme" parent= "Theme.AppCompat.Light.DarkActionBar" > <!--Customize R theme here. --> <item name= "colorprimary" > #03A9F4 </item> <item name= "Android:textcolorprimary" > #ffffff ;/item> <item name= "Android:windowbackground" > @color/background_material_light</item> <item name = "Coloraccent" > #00BCD4 </item> <item name= "Colorcontrolnormal" > #00BCD4 </item> <item name= " TitleStyle "> @style/daytitlestyle</item> <item name=" Contentstyle "> @style/daycontentstyle</item
    > <item name= "BUTTONBG" > #2196F3 </item> <item name= "Buttontextcolor" > #ffffff </item>
  <item name= "Checktextcolor" > #2196F3 </item> <item name= "Switchtextcolor" > #2196F3 </item> </style> <style name= "Daytitlestyle" > <item name= "Android:textcolor" > #212121 </item> ; Item Name= "Android:tExtsize ">20sp</item> <item name=" Android:layout_margin ">8dp</item> </style> <style Name= "Daycontentstyle" > <item name= "Android:textcolor" > #9C27B0 </item> <item name= "Android:textsi Ze ">16sp</item> <item name=" Android:layout_margin ">16dp</item> <item name=" Android:maxline S ">10</item> </style> </resources>

Night Theme

<resources> <style name= "Nighttheme" parent= "Theme.AppCompat.Light.DarkActionBar" > <!--Customize y We theme here. --> <item name= "colorprimary" > #00796B </item> <item name= "Android:textcolorprimary" > #212121 ;/item> <item name= "Android:windowbackground" > @color/background_material_dark</item> <item "Coloraccent" > #00796B </item> <item name= "Colorcontrolnormal" > #212121 </item> <item name= "t Itlestyle "> @style/nighttitlestyle</item> <item name=" Contentstyle "> @style/nightcontentstyle</
    item> <item name= "BUTTONBG" > #00796B </item> <item name= "Buttontextcolor" > #9E9E9E </item> <item name= "Checktextcolor" > #212121 </item> <item name= "Switchtextcolor" > #212121 </item> & lt;/style> <style name= "Nighttitlestyle" > <item name= "Android:textcolor" > #212121 </item> &L T;item Name= "anDroid:textsize ">20sp</item> <item name=" Android:layout_margin ">8dp</item> </style> ; style name= "Nightcontentstyle" > <item name= "Android:textcolor" > #212121 </item> <item name= "Andro Id:textsize ">16sp</item> <item name=" Android:layout_margin ">16dp</item> <item name=" Androi D:maxlines ">10</item> </style> </resources>

In these two sets of topics, each attribute definition is exactly the same, but the value of the property is not the same, and there is a code in the style of Daytheme and Nighttheme:

<item name= "TitleStyle" > @style/daytitlestyle</item>
<item name= "Contentstyle" > @style daycontentstyle</item>
<item name= "BUTTONBG" > #2196F3 </item>
<item name= " Buttontextcolor "> #ffffff </item>
<item name=" Checktextcolor "> #2196F3 </item>
< Item Name= "Switchtextcolor" > #2196F3 </item>

These properties do not normally exist in the style, which are custom attributes that control the properties of certain controls or layouts, which are defined in the attr file:

<?xml version= "1.0" encoding= "Utf-8"?>
<resources> <attr name= "Contentstyle" format= "
  Reference "/> <attr name=" TitleStyle "format=" reference "/> <attr name=" BUTTONBG "format="
  Reference|color "/> <attr name= buttontextcolor" format= "Reference|color"/> <attr name=
  " Checktextcolor "format=" Reference|color "/> <attr name=" Switchtextcolor "format=" Reference|color "/>

You can then refer to it in the layout:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http:// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:o" rientation= "Vertical" tools:context= ". Mainactivity "> <textview style="? Attr/titlestyle "Android:layout_width=" Wrap_content "Android:layout_" height= "Wrap_content" android:text= "@string/title"/> <textview style= "? Attr/contentstyle" Android:la Yout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "@string/hello_world"/> <Che Ckbox android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "CheckBox" and Roid:textcolor= "Attr/checktextcolor"/> <checkbox android:layout_width= "Wrap_content" Android:layout_hei ght= "Wrap_content" android:text= "CheckBox" android:textcolor= "Attr/checktextcolor"/> <switch D:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Switch" android:textcolor= "? Attr/switchText Color "/> <button android:id=" @+id/btn_setting "android:layout_width=" Wrap_content "Android:layout_he" ight= "Wrap_content" android:text= set "android:background="? Attr/buttonbg "android:textcolor="? Attr/buttonTextC Olor "/> </LinearLayout>

Finally, it's OK to use them throughout the app theme's style. What is the benefit of doing so? We all know that the app setting theme is all about setting a style, while some of the controls or layout backgrounds or style styles in the app need not be the same as the entire theme style, by setting a custom attribute to achieve the goal by giving a different value to the custom attribute in the app's style.

Toggle Theme

Well, with two sets of themes, the next is through the code to control the switch between the topic, control the theme of the switch is actually through Settheme (r.style.*), to set up a different style to achieve the interface style of transformation, but this method Settheme () It is only valid before the Setcontentview () method, so if you want to call this method elsewhere to toggle the theme It's definitely not going to work, so here are two difficulties?

1, how to deal with the current settings interface in the switch theme after switching theme style

2, how to deal with the previous open interface let them switch theme style

The answer I give here is:

1. Use the Activity.recreate () method in the settings interface of the current toggle theme, which is to call this method to destroy the current activity instance and recreate an activity instance when the current active configuration changes. So visible through this method it is easy to solve the problem one, because it will recreate a new activity instance.

2, here I use the method is by setting Intent FLAG to update the effect of the activity before, by setting up Mintent.setflags (Intent.flag_activity_new_task | Intent.flag_activity_clear_task); Let it clear the previous activity before creating a new activity so that the theme can be updated when the previous interface is returned. "Note" If more than one interface can be set by setting the main interface mainactivity Launchmode as Singletask, clear the other interface when returning to the main interface to update the theme

For the above method (if there is a better way to welcome the notification, thank you very much!) )

Code implementation

Finally put the code:
Set the theme by setting the tool class with a theme, setting the theme before the Setcontentview () method for each activity:
To set the Theme tool class:

public class Themechangeutil {public
  static Boolean ischange = false;
  public static void Changetheme (activity activity) {
    if (ischange) {
      activity.settheme (r.style.nighttheme);

To set the interface:

 public class Changetheme extends appcompatactivity {@Override protected void Oncrea
    Te (Bundle savedinstancestate) {themechangeutil.changetheme (this);
    Super.oncreate (savedinstancestate);

    Setcontentview (R.layout.activity_change);
    Button mchangebtn = (button) Findviewbyid (R.id.btn_change); Mchangebtn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {if
        (themechangeutil.ischange) {themechangeutil.ischange = false;
        else {Themechangeutil.ischange = true;
  ChangeTheme.this.recreate ();//Recreate the current Activity Instance}});
    @Override public void onbackpressed () {super.onbackpressed ();
    Intent mintent = new Intent (this, mainactivity.class); Mintent.setflags (Intent.flag_activity_new_task |
    StartActivity (mintent);
  Finish (); }

Main interface:

public class Mainactivity extends Appcompatactivity {
  protected void OnCreate (Bundle Savedinstancestate) {
    themechangeutil.changetheme (this);
    Super.oncreate (savedinstancestate);
    Setcontentview (r.layout.activity_main);

    Button msettingbtn = (button) Findviewbyid (r.id.btn_setting);
    Msettingbtn.setonclicklistener (New View.onclicklistener () {
      @Override public
      void OnClick (View v) {
        MainActivity.this.startActivity (New Intent (Mainactivity.this, Changetheme.class));}}

The above is the android theme switch in the day/night mode of the detailed process and code, first to give you a simple display of code, and then the detailed introduction of the process and code, the need for a friend reference.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.