The implementation of dynamically changing themes in Android apps

Source: Internet
Author: User

In android Apps We may need to switch modes, such as switching to night mode for easy reading at night. In this paper, we refer to some information on the Internet and combine the examples to realize the effect of changing theme dynamically.

The implementation of the theme theme in Android can use the setTheme (int) method in the activity , The description of this method in the SDK is:

// Set The base theme for this context. Note that this should is called before any views is instantiated in the Context (for example before calling Android.app.a Ctivity.setcontentview or android.view.LayoutInflater.inflate). // need to be used before the Setcontentview function or the inflate function. 

As follows:

Implementation steps:

You first need to define a property that is used to assign a property to the control, which is equivalent to the "variable" of the control's property value.

In attrs.xml , three attributes are defined, and the format of the property is reference|color

<Resources>    <attrname= "BUTTON_BG"format= "Reference|color" />    <attrname= "ACTIVITY_BG"format= "Reference|color" />    <attrname= "TEXT_CL"format= "Reference|color" /></Resources>

Next, in styles.xml , write your custom Theme

<stylename= "Appbasetheme"Parent= "Android:Theme.Light">    </style>    <stylename= "Apptheme"Parent= "Appbasetheme">        <Itemname= "TEXT_CL">#ffffff</Item>        <Itemname= "BUTTON_BG">#000000</Item>        <Itemname= "ACTIVITY_BG">#ffffff</Item>    </style>    <stylename= "Darktheme"Parent= "Appbasetheme">        <Itemname= "TEXT_CL">#000000</Item>        <Itemname= "BUTTON_BG">#ffffff</Item>        <Itemname= "ACTIVITY_BG">#000000</Item></style>

Select a pattern as the default theme for a program, note that because I am the style of the view defined in the layout file, you need to add item to each custom theme you use in order to ensure that no resources are found when the theme switch. The item here is consistent with the format of the TextColor property of Text_cl and view.

Android manifest file:

<?XML version= "1.0" encoding= "Utf-8"?><Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.example.testandroidsettheme"Android:versioncode= "1"Android:versionname= "1.0" >    <USES-SDKandroid:minsdkversion= "8"android:targetsdkversion= "+" />    <ApplicationAndroid:allowbackup= "true"Android:name= "COM.EXAMPLE.TESTANDROIDSETTHEME.APP.MYAPP"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" >        <ActivityAndroid:name= "Com.example.testandroidsettheme.MainActivity"Android:label= "@string/app_name" >            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.MAIN" />                <categoryAndroid:name= "Android.intent.category.LAUNCHER" />            </Intent-filter>        </Activity>    </Application></Manifest>

I will android:theme= "@style/apptheme" as the default style.

Main interface layout:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:background= "? Activity_bg"android:gravity= "Center"android:orientation= "vertical" >    <ButtonAndroid:id= "@+id/button0"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:background= "? Button_bg"Android:textcolor= "? Text_cl"Android:text= "Set Theme" /></LinearLayout>

In the layout file, the background property of the button takes the property value of the button_bg under the current theme , the external linearlayout takes the property value of the activity_bg under the current theme , When filling in this property value, you need to add "?" earlier to indicate that this is a variable in a style .

In the activity where you need to toggle the display of different theme , some blogs are used in the button Click event

SetTheme (int);

Recreate ();

Way, I found that this way could not achieve theme switching because the recreate () method would recreate this activity, before the SetTheme () is not valid. My implementation is as follows:

 Public classMainactivityextendsActivity { PublicButton Button0; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); MYAPP app= (MyApp) mainactivity. This. Getapplication (); if(App.theme = = 0){            //Use the default theme}Else{            //use a custom themeSetTheme (App.theme);        } setcontentview (R.layout.activity_main); Button0= (Button) This. Findviewbyid (R.id.button0); Button0.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {MyApp app= (MyApp) mainactivity. This. Getapplication (); App.theme=R.style.darktheme;            Recreate ();    }        }); }} Public classMyAppextendsapplication{ Public intTheme = 0;}

Before the Setcontentview () method call in this activityoncreate (), the current theme is judged, and Settheme () is called to implement the effect of changing the theme.

Note: This method of switching theme is not very friendly because there may be a splash screen when the activity is re-created. Better solution if the client is using a screenshot, and fade the image of the excessive way, the specific implementation still needs to learn.

Reference: HTTP://WWW.KYMJS.COM/CODE/2015/05/26/01/

The implementation of dynamically changing themes in Android apps

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.