Android 實現切換主題皮膚功能(類似於眾多app中的 夜間模式,主題包等)

希爾瓦娜斯女神發表於2015-11-16

首先來個最簡單的一鍵切換主題功能,就做個白天和晚上的主題好了。

先看我們的styles檔案:

 1 <resources>
 2 
 3     <!-- Base application theme. -->
 4     <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
 5         <!-- Customize your theme here. -->
 6         <item name="colorPrimary">@color/colorPrimary</item>
 7         <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
 8         <item name="colorAccent">@color/colorAccent</item>
 9     </style>
10     <style name="AppTheme.NoActionBar">
11         <item name="windowActionBar">false</item>
12         <item name="windowNoTitle">true</item>
13     </style>
14     <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
15     <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
16 
17     <!--白天主題-->
18     <style name="dayTheme" parent="AppTheme">
19           <item name="android:textColor">#525252</item>
20         <item name="android:background">#f7f7f7</item>
21     </style>
22 
23     <!--夜間主題-->
24     <style name="nightTheme" parent="AppTheme">
25         <item name="android:textColor">#868a96</item>
26         <item name="android:background">#1e1e2a </item>
27     </style>
28 
29 
30 </resources>

好,然後我們來看看主要activity

package com.example.administrator.mainchangethemeapp;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //sputils是對SharedPreferences的封裝,程式碼就不上了,大家理解意思就行了
        if(SPUtils.get(this,"theme","dayTheme").equals("dayTheme"))
        {
            //預設是白天主題
            setTheme(R.style.dayTheme);
        }else
        {
            //否則是晚上主題
            setTheme(R.style.nightTheme);
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        tv=(TextView)this.findViewById(R.id.tv);
        tv.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                if(SPUtils.get(MainActivity.this,"theme","dayTheme").equals("dayTheme"))
                {
                    SPUtils.put(MainActivity.this,"theme","nightTheme");
                }else
                {
                    SPUtils.put(MainActivity.this, "theme", "dayTheme");
                }
                recreate();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

然後來看下效果:

 

當然了,上面這個demo實際上是有缺陷的。有人會說了 你看人家新浪微博,那麼多主題,你要是用這種方法,你這個app得有多大,

能做成微博那樣要用什麼就去下載什麼麼?答案是可以的。其實方案也很簡單。

這種方案的思路就是,把主題包 額外做成一個apk,注意這個apk 是不會在桌面顯示的。你只能在設定裡的app列表裡找到他。

然後在你的主activity裡 取這個apk裡的資源 即可。這裡我也把這種方案的程式碼寫一遍。注意下載apk 安裝apk的程式碼我就不寫了。

我們就假設 我們要切換的主題就是系統自帶的主題就行了,我們的主activity 使用的是白天主題。然後我們的子app裡面

為了簡化程式碼,我們就不放自定義主題了,就使用android studio 原始的程式碼,一步步來,

先放上子app裡的styles檔案,其實這個裡面一行程式碼都沒更改,全是ide自己生成的:

 1 <resources>
 2 
 3     <!-- Base application theme. -->
 4     <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
 5         <!-- Customize your theme here. -->
 6         <item name="colorPrimary">@color/colorPrimary</item>
 7         <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
 8         <item name="colorAccent">@color/colorAccent</item>
 9     </style>
10     <style name="AppTheme.NoActionBar">
11         <item name="windowActionBar">false</item>
12         <item name="windowNoTitle">true</item>
13     </style>
14     <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
15     <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
16 
17 
18 </resources>

然後就是子activity裡的 配置檔案manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.administrator.sonproject" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>
        </activity>
    </application>

</manifest>

注意這裡 

<category android:name="android.intent.category.LAUNCHER" />

的這行程式碼 我是沒寫的。這樣就是保證在這個apk 安裝好以後不會在桌面出現。
然後我們來看看主activity程式碼
 1 package com.example.administrator.mainchangethemeapp;
 2 
 3 import android.content.Context;
 4 import android.content.SharedPreferences;
 5 import android.content.pm.PackageManager;
 6 import android.content.res.TypedArray;
 7 import android.os.Bundle;
 8 import android.support.design.widget.FloatingActionButton;
 9 import android.support.design.widget.Snackbar;
10 import android.support.v4.app.Fragment;
11 import android.support.v7.app.AppCompatActivity;
12 import android.support.v7.widget.Toolbar;
13 import android.util.Log;
14 import android.util.TypedValue;
15 import android.view.View;
16 import android.view.Menu;
17 import android.view.MenuItem;
18 import android.widget.TextView;
19 
20 public class MainActivity extends AppCompatActivity {
21 
22     private TextView tv;
23 
24     @Override
25     protected void onCreate(Bundle savedInstanceState) {
26         //sputils是對SharedPreferences的封裝,程式碼就不上了,大家理解意思就行了
27         if (SPUtils.get(this, "theme", "dayTheme").equals("dayTheme")) {
28             //預設是白天主題
29             setTheme(R.style.dayTheme);
30         } else {
31             //否則是晚上主題,這裡晚上主題我們就去載入我們晚上主題apk裡的資源
32             int resourceId = getResourceId(getPackageContext(this, "com.example.administrator.sonproject"), "style", "AppTheme");
33             setTheme(resourceId);
34         }
35         super.onCreate(savedInstanceState);
36         setContentView(R.layout.activity_main);
37         tv = (TextView) this.findViewById(R.id.tv);
38         tv.setOnClickListener(new View.OnClickListener() {
39 
40             @Override
41             public void onClick(View v) {
42                 if (SPUtils.get(MainActivity.this, "theme", "dayTheme").equals("dayTheme")) {
43                     SPUtils.put(MainActivity.this, "theme", "nightTheme");
44                 } else {
45                     SPUtils.put(MainActivity.this, "theme", "dayTheme");
46                 }
47                 recreate();
48             }
49         });
50     }
51 
52     @Override
53     public boolean onCreateOptionsMenu(Menu menu) {
54         // Inflate the menu; this adds items to the action bar if it is present.
55         getMenuInflater().inflate(R.menu.menu_main, menu);
56         return true;
57     }
58 
59     @Override
60     public boolean onOptionsItemSelected(MenuItem item) {
61         // Handle action bar item clicks here. The action bar will
62         // automatically handle clicks on the Home/Up button, so long
63         // as you specify a parent activity in AndroidManifest.xml.
64         int id = item.getItemId();
65 
66         //noinspection SimplifiableIfStatement
67         if (id == R.id.action_settings) {
68             return true;
69         }
70 
71         return super.onOptionsItemSelected(item);
72     }
73 
74 
75     /**
76      * 獲取其他apk的context
77      * @param context
78      * @param packageName
79      * @return
80      */
81     public static Context getPackageContext(Context context, String packageName) {
82         try {
83             return context.createPackageContext(packageName, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
84         } catch (PackageManager.NameNotFoundException e) {
85             e.printStackTrace();
86         }
87         return null;
88     }
89 
90     //獲取指定context的 type裡面的 name屬性
91     public static int getResourceId(Context context, String type, String name) {
92         return context.getResources().getIdentifier(name, type, context.getPackageName());
93     }
94 }

你看,到這裡 我們就實現了,動態載入主題的方式了。當然了,到這裡依舊是不完美的,因為settheme方法大家都知道一定要重啟activity才有效啊。這樣就不好了。

體驗並非最佳。總是給人很突兀的感覺。而且我們都知道重啟activity的成本很大。要考慮很多生命週期之類的東西。那我們繼續往下看,看看有什麼比較好的解決方案能解決這個問題。

首先 我們可以考慮一下這個問題,所謂的切換主題 之類的,無非就是把你那些控制元件的 背景色啊 字型顏色之類的 改變了一下。對於一個app來說,使用者一般只有一個介面 會有切換主題的這個入口,

換句話說,我們的app裡面 只有這一個activity 需要實現 不重啟activity就切換 控制元件style的功能,其他activity我們是不需要實現這個功能的,因為再切換過去的時候基本上都會走oncreate。所以

我們只需要考慮這個 有切換主題按鈕的 這個activity能實現 不重啟activity就換皮膚的功能就可以了。其他activity不需要考慮。so 這樣一想 這個功能就簡單清晰了很多。

首先我們可以自定義2個屬性,我們把他放在attrs 這個xml裡面

1 <?xml version="1.0" encoding="utf-8"?>
2 <resources>
3     <!-- 首先自定義屬性,這裡我們為了簡便 只自定義了這2種屬性,如果你要自己做的話 看需求可以增加屬性-->
4     <!-- 另外注意我們這裡並沒有使用declare-styleable  來包裹這裡的2個屬性 好處就是在xml檔案裡 不用另外定義字首了-->
5     <attr name="custom_background" format="reference|color"/>
6     <attr name="custom_textcolor" format="reference|color"/>
7 </resources>

 

然後我們去定義一下我們的主題:

 1 <resources>
 2 
 3     <!-- 這裡就設定2個最簡單的 主題就行了,-->
 4     <!--白天主題-->
 5     <style name="dayTheme" >
 6         <item name="custom_background">#f7f7f7</item>
 7         <item name="custom_textcolor">#525252</item>
 8     </style>
 9 
10     <!--晚上主題-->
11     <style name="nightTheme">
12         <item name="custom_background">#1e1e2a</item>
13         <item name="custom_textcolor">#868a96</item>
14     </style>
15 </resources>

然後我們來寫一下mainactivity的xml佈局檔案,我們假設這個佈局是非常簡單的:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <com.example.administrator.mainchangethemeapp.ThemeRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:background="?attr/custom_background"
 6     android:id="@+id/mainview"
 7     >
 8 
 9     <com.example.administrator.mainchangethemeapp.ThemeTextView
10         android:id="@+id/tv"
11         android:layout_width="100dp"
12         android:layout_height="100dp"
13         android:layout_centerInParent="true"
14         android:text="一鍵切換主題"
15         android:background="?attr/custom_background"
16         android:textColor="?attr/custom_textcolor"
17         />
18 
19 </com.example.administrator.mainchangethemeapp.ThemeRelativeLayout>

你看這個佈局裡面 就一個relativelayout和一個textview。 和以前xml唯一的區別就是這裡backaground和textcolor使用的值 是我們前面定義好的屬性了(但是要注意 這屬性是沒有值的 賦值的操作放在java程式碼裡實現)。同時這2個控制元件 也並非是系統控制元件 而是自定義控制元件。然後我們看看這個自定義控制元件是怎麼寫的。注意我這裡就做了2個自定義控制元件,如果你們的那個切換主題的入口頁面裡面有其他控制元件的話,就要學著下面的方法 自己擴充一下了,其實也很簡單的。

首先呢,我們來定義一個介面,誰實現了這個介面 就說明這個控制元件可以不啟動activity直接換膚!

 1 package com.example.administrator.mainchangethemeapp;
 2 
 3 import android.content.res.Resources;
 4 import android.view.View;
 5 
 6 /**
 7  * Created by Administrator on 2015/11/14.
 8  */
 9 public interface ThemeUIInterface {
10 
11     public View getView();
12     public  void setTheme(Resources.Theme themeId);
13 }

然後我們來看看2個自定義控制元件怎麼寫:

 1 package com.example.administrator.mainchangethemeapp;
 2 
 3 import android.content.Context;
 4 import android.content.res.Resources;
 5 import android.util.AttributeSet;
 6 import android.util.Log;
 7 import android.view.View;
 8 import android.widget.RelativeLayout;
 9 
10 /**
11  * Created by Administrator on 2015/11/14.
12  */
13 public class ThemeRelativeLayout extends RelativeLayout implements ThemeUIInterface{
14 
15     private int attr_background = -1;
16 
17     public ThemeRelativeLayout(Context context) {
18         super(context);
19     }
20 
21     public ThemeRelativeLayout(Context context, AttributeSet attrs) {
22         super(context, attrs);
23         this.attr_background =ViewAttributeUtil.getBackgroundAttibute(attrs);
24     }
25 
26     public ThemeRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
27         super(context, attrs, defStyleAttr);
28         this.attr_background =ViewAttributeUtil.getBackgroundAttibute(attrs);
29 
30     }
31 
32 
33     @Override
34     public View getView() {
35         return this;
36     }
37 
38     @Override
39     public void setTheme(Resources.Theme themeId) {
40         if(attr_background!=-1) {
41             ViewAttributeUtil.applyBackgroundDrawable(this, themeId, attr_background);
42         }
43     }
44 }
 1 package com.example.administrator.mainchangethemeapp;
 2 
 3 import android.content.Context;
 4 import android.content.res.Resources;
 5 import android.util.AttributeSet;
 6 import android.view.View;
 7 import android.widget.TextView;
 8 
 9 /**
10  * Created by Administrator on 2015/11/16.
11  */
12 public class ThemeTextView extends TextView implements ThemeUIInterface{
13 
14     private int attr_drawable=-1;
15     private int attr_textColor=-1;
16 
17     public ThemeTextView(Context context) {
18         super(context);
19     }
20 
21     public ThemeTextView(Context context, AttributeSet attrs) {
22         super(context, attrs);
23         this.attr_drawable = ViewAttributeUtil.getBackgroundAttibute(attrs);
24         this.attr_textColor = ViewAttributeUtil.getTextColorAttribute(attrs);
25     }
26 
27     public ThemeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
28         super(context, attrs, defStyleAttr);
29         this.attr_drawable = ViewAttributeUtil.getBackgroundAttibute(attrs);
30         this.attr_textColor = ViewAttributeUtil.getTextColorAttribute(attrs);
31     }
32 
33     @Override
34     public View getView() {
35         return this;
36     }
37 
38     @Override
39     public void setTheme(Resources.Theme themeId) {
40         if (attr_drawable != -1) {
41             ViewAttributeUtil.applyBackgroundDrawable(this, themeId, attr_drawable);
42         }
43         if (attr_textColor != -1) {
44             ViewAttributeUtil.applyTextColor(this, themeId, attr_textColor);
45         }
46     }
47 }

看上去 其實也蠻簡單的對吧,無非就相比傳統控制元件,他對外暴露了 setTheme這個方法罷了,而這個setTheme方法 其實就做了一件事,呼叫系統自己的方法重新set那些屬性罷了。

 1 package com.example.administrator.mainchangethemeapp;
 2 
 3 
 4 import android.content.res.Resources;
 5 import android.content.res.TypedArray;
 6 import android.graphics.drawable.Drawable;
 7 import android.util.AttributeSet;
 8 import android.util.Log;
 9 import android.widget.ImageView;
10 import android.widget.TextView;
11 
12 public class ViewAttributeUtil {
13 
14     public static int getAttributeValue(AttributeSet attr, int paramInt) {
15         int value = -1;
16         int count = attr.getAttributeCount();
17         for(int i = 0; i <count;i++) {
18             if(attr.getAttributeNameResource(i) == paramInt) {
19                 String str = attr.getAttributeValue(i);
20                 if(null != str && str.startsWith("?")) {
21                     value = Integer.valueOf(str.substring(1, str.length())).intValue();
22                     return value;
23                 }
24             }
25         }
26         return value;
27     }
28 
29     public static int getBackgroundAttibute(AttributeSet attr) {
30         return getAttributeValue(attr , android.R.attr.background);
31     }
32 
33 
34     public static int getTextColorAttribute(AttributeSet attr) {
35         return getAttributeValue(attr, android.R.attr.textColor);
36     }
37 
38     public static void applyBackgroundDrawable(ThemeUIInterface ci, Resources.Theme theme, int paramInt) {
39         TypedArray ta = theme.obtainStyledAttributes(new int[]{paramInt});
40         Drawable drawable = ta.getDrawable(0);
41         if(null != ci) {
42             (ci.getView()).setBackgroundDrawable(drawable);
43         }
44         ta.recycle();
45     }
46     public static void applyTextColor(ThemeUIInterface ci, Resources.Theme theme, int paramInt) {
47         TypedArray ta = theme.obtainStyledAttributes(new int[]{paramInt});
48         int resourceId = ta.getColor(0,0);
49         if(null != ci && ci instanceof TextView) {
50             ((TextView)ci.getView()).setTextColor(resourceId);
51         }
52         ta.recycle();
53     }
54 
55 }

好,到這裡 脈絡就逐漸清晰了,我們就看看主activity裡怎麼寫了:

 1 package com.example.administrator.mainchangethemeapp;
 2 
 3 import android.app.Activity;
 4 import android.os.Bundle;
 5 import android.view.Menu;
 6 import android.view.MenuItem;
 7 import android.view.View;
 8 import android.widget.TextView;
 9 
10 public class MainActivity extends Activity {
11 
12     private TextView tv;
13 
14     private View view;
15 
16     @Override
17     protected void onCreate(Bundle savedInstanceState) {
18         //這行程式碼千萬不能漏掉,否則會報錯的。因為你在xml裡 的那些值 根本就沒有實際的值,如果不在這裡強制性的setTheme就直接報錯了
19         //在實際使用中 我們當然可以把這個方法 放在baseactivity裡面。我們這裡預設主題就白天吧
20         setTheme(R.style.dayTheme);
21         super.onCreate(savedInstanceState);
22         setContentView(R.layout.activity_main);
23         //這個就是跟佈局
24         view = this.findViewById(R.id.mainview);
25         tv = (TextView) this.findViewById(R.id.tv);
26         tv.setOnClickListener(new View.OnClickListener() {
27 
28             @Override
29             public void onClick(View v) {
30 
31                 //這邊邏輯沒啥好說的 其實可以不需要看啊,就是白天就切換到黑夜 黑夜就切換到白天唄
32                 if (SPUtils.get(MainActivity.this, "theme", "dayTheme").equals("dayTheme")) {
33                     SPUtils.put(MainActivity.this, "theme", "nightTheme");
34                     setTheme(R.style.nightTheme);
35                 } else {
36                     SPUtils.put(MainActivity.this, "theme", "dayTheme");
37                     setTheme(R.style.dayTheme);
38                 }
39                 //這個方法就是實現不重啟頁面切換主題的
40                 ThemeUiUtil.changeTheme(view, getTheme());
41             }
42         });
43     }
44 
45     @Override
46     public boolean onCreateOptionsMenu(Menu menu) {
47         // Inflate the menu; this adds items to the action bar if it is present.
48         getMenuInflater().inflate(R.menu.menu_main, menu);
49         return true;
50     }
51 
52     @Override
53     public boolean onOptionsItemSelected(MenuItem item) {
54         // Handle action bar item clicks here. The action bar will
55         // automatically handle clicks on the Home/Up button, so long
56         // as you specify a parent activity in AndroidManifest.xml.
57         int id = item.getItemId();
58 
59         //noinspection SimplifiableIfStatement
60         if (id == R.id.action_settings) {
61             return true;
62         }
63 
64         return super.onOptionsItemSelected(item);
65     }
66 
67 }

然後看一下切換主題的方法是怎麼做的:

 1 package com.example.administrator.mainchangethemeapp;
 2 
 3 import android.content.res.Resources;
 4 import android.util.Log;
 5 import android.view.View;
 6 import android.view.ViewGroup;
 7 import android.widget.AbsListView;
 8 
 9 import java.lang.reflect.Field;
10 import java.lang.reflect.InvocationTargetException;
11 import java.lang.reflect.Method;
12 
13 /**
14  * Created by Administrator on 2015/11/14.
15  */
16 public class ThemeUiUtil {
17     /**
18      * 切換應用主題
19      *
20      * @param rootView
21      */
22     public static void changeTheme(View rootView, Resources.Theme theme) {
23         //這裡邏輯很簡單 就是遞迴呼叫changeTheme-----遞迴呼叫setTheme了。
24         //注意 你們如果是listview也包含在裡面的話 listview自定義實現介面的時候要稍微複雜一些,看你們需要不需要也重新整理listview裡的item了
25         //這裡為了簡單 我就不寫那麼複雜了,就這一個邏輯:先set自己的theme 然後遍歷自己的子控制元件 逐一set
26         if (rootView instanceof ThemeUIInterface) {
27             ((ThemeUIInterface) rootView).setTheme(theme);
28             if (rootView instanceof ViewGroup) {
29                 int count = ((ViewGroup) rootView).getChildCount();
30                 for (int i = 0; i < count; i++) {
31                     changeTheme(((ViewGroup) rootView).getChildAt(i), theme);
32                 }
33             }
34         }
35     }
36 
37 
38 }

 

你看,到這裡 我們不重啟activity實現換膚的功能就基本實現了,當然要做的完美的話 還需要各位自己擴充一下 其他控制元件。但是思路都是一樣的。

 

 

看到這裡 有人仍然會說,你這個雖然沒有重啟activity,但是還是不好看呀,還是顯的突兀了,能否做到知乎 android app那樣 切換白天黑夜主題的時候 顯的很柔順呢。

答案是可以的,而且解決方案也比較簡單。就是給個動畫就完事了,在切換前 先保留一下 之前介面的bitmap 然後切換皮膚的的時候 把這個bitmap 顯示出來以後 然後改變他的

alpha值 就可以了,當全部動畫顯示結束以後 把那些不需要的資源全部釋放 就ok了!

來看下程式碼,這裡就放出點選事件的程式碼了,其他地方與前面的程式碼一致:

 1 {
 2 
 3                 //我們先取這個根佈局的 bitmap快取 這個實際上跟截圖是差不多的一個東西。
 4                 view.setDrawingCacheEnabled(true);
 5                 view.buildDrawingCache(true);
 6                 final Bitmap localBitmap = Bitmap.createBitmap(view.getDrawingCache());
 7                 view.setDrawingCacheEnabled(false);
 8 
 9                 //這邊邏輯沒啥好說的 其實可以不需要看啊,就是白天就切換到黑夜 黑夜就切換到白天唄
10                 if (SPUtils.get(MainActivity.this, "theme", "dayTheme").equals("dayTheme")) {
11                     SPUtils.put(MainActivity.this, "theme", "nightTheme");
12                     setTheme(R.style.nightTheme);
13                 } else {
14                     SPUtils.put(MainActivity.this, "theme", "dayTheme");
15                     setTheme(R.style.dayTheme);
16                 }
17                 //我們new出來的這個蒙版view --mengbanview 就把他放到跟佈局view裡面 並且讓他充滿 同時這個view的background就是截圖前我們的那個截圖bitmap
18                 final View mengbanView = new View(getApplicationContext());
19                 mengbanView.setBackgroundDrawable(new BitmapDrawable(getResources(), localBitmap));
20                 ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
21                 ((ViewGroup) view).addView(mengbanView, params);
22                 mengbanView.animate().alpha(0).setDuration(400).setListener(new Animator.AnimatorListener() {
23                     @Override
24                     public void onAnimationStart(Animator animation) {
25                         //這個方法就是實現不重啟頁面切換主題的
26                         ThemeUiUtil.changeTheme(view, getTheme());
27                     }
28 
29                     @Override
30                     public void onAnimationEnd(Animator animation) {
31                         //動畫結束的時候移出這個蒙版view 並釋放bitmap
32                         ((ViewGroup) view).removeView(mengbanView);
33                         localBitmap.recycle();
34                     }
35 
36                     @Override
37                     public void onAnimationCancel(Animator animation) {
38 
39                     }
40 
41                     @Override
42                     public void onAnimationRepeat(Animator animation) {
43 
44                     }
45                 }).start();
46 
47 
48             }

最後來看下效果是否和知乎一樣:

大功告成,看上去自然多了!

 

 

 

 

 

 

 

 

 

相關文章