Android夜間模式最佳實踐
由于Android的設置中并沒有夜間模式的選項,對于喜歡睡前玩手機的用戶,只能簡單的調(diào)節(jié)手機屏幕亮度來改善體驗。目前越來越多的應用開始把夜間模式加到自家應用中,沒準不久google也會把這項功能添加到Android系統(tǒng)中吧。
業(yè)內(nèi)關(guān)于夜間模式的實現(xiàn),有兩種主流方案,各有其利弊,我較為推崇第三種方案:
1、通過切換theme來實現(xiàn)夜間模式。
2、通過資源id映射的方式來實現(xiàn)夜間模式。
3、通過修改uiMode來切換夜間模式。
值得一提的是,上面提到的幾種方案,都是資源內(nèi)嵌在Apk中的方案,像新浪微博那種需要通過下載方式實現(xiàn)的夜間模式方案,網(wǎng)上有很多介紹,這里不去討論。
下面簡要描述下幾種方案的實現(xiàn)原理:
一、通過切換theme來實現(xiàn)夜間模式
首先在attrs.xml中,為需要隨theme變化的內(nèi)容定義屬性
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="textColor" format="color|reference" /> <attr name="mainBackground" format="color|reference" /> </resources>
其次在不同的theme中,對屬性設置不同的值,在styles.xml中定義theme如下
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- 默認 --> <style name="ThemeDefault" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="mainBackground">#ffffff</item> <item name="textColor">#000000</item> </style> <!-- 夜間 --> <style name="ThemeNight" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="mainBackground">#000000</item> <item name="textColor">#ffffff</item> </style> </resources>
在布局文件中使用對應的值,通過?attr/屬性名,來獲取不同theme對應的值。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android="@+id/main_screen" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="?attr/mainBackground"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="改變Theme" android:onClick="changeTheme" android:textColor="?attr/textColor"/> </LinearLayout>
在Activity中調(diào)用如下changeTheme方法,其中isNightMode為一個全局變量用來標記當前是否為夜間模式,在設置完theme后,還需要調(diào)用restartActivity或者setContentView重新刷新UI。
public void changeTheme() { if (isNightMode) { setTheme(R.style.ThemeDefault); isNightMode = false; } else { setTheme(R.style.ThemeNight); isNightMode = true; } setContentView(R.layout.activity_main); }
到此即完成了一個夜間模式的簡單實現(xiàn),包括Google自家在內(nèi)的很多應用都是采用此種方式實現(xiàn)夜間模式的,這應該也是Android官方推薦的方式。
但這種方式有一些不足,規(guī)模較大的應用,需要隨theme變化的屬性會很多,都需要逐一定義,有點麻煩,另外一個缺點是要使得新theme生效,一般需要restartActivity來切換UI,會導致切換主題時界面閃爍。
不過也可以通過調(diào)用如下updateTheme方法,只更新需要更新的部分,規(guī)避閃爍問題,只是需要寫上一堆updateTheme方法。
private void updateTheme() { TypedValue typedValue = new TypedValue(); Resources.Theme theme = getTheme(); theme.resolveAttribute(R.attr.textColor, typedValue, true); findViewById(R.id.button).setBackgroundColor(typedValue.data); theme.resolveAttribute(R.attr.mainBackground, typedValue, true); findViewById(R.id.main_screen).setBackgroundColor(typedValue.data); }
二、通過資源id映射的方式實現(xiàn)夜間模式
通過id獲取資源時,先將其轉(zhuǎn)換為夜間模式對應id,再通過Resources來獲取對應的資源。
public static Drawable getDrawable(Context context, int id) { return context.getResources().getDrawable(getResId(id)); } public static int getResId(int defaultResId) { if (!isNightMode()) { return defaultResId; } if (sResourceMap == null) { buildResourceMap(); } int themedResId = sResourceMap.get(defaultResId); return themedResId == 0 ? defaultResId : themedResId; }
這里是通過HashMap將白天模式的resId和夜間模式的resId來一一對應起來的。
private static void buildResourceMap() { sResourceMap = new SparseIntArray(); sResourceMap.put(R.drawable.common_background, R.drawable.common_background_night); // ... }
這個方案簡單粗暴,麻煩的地方和第一種方案一樣:每次添加資源都需要建立映射關(guān)系,刷新UI的方式也與第一種方案類似,貌似今日頭條,網(wǎng)易新聞客戶端等主流新聞閱讀應用都是通過這種方式實現(xiàn)的夜間模式。
三、通過修改uiMode來切換夜間模式
首先將獲取資源的地方統(tǒng)一起來,使用Application對應的Resources,在Application的onCreate中調(diào)用ResourcesManager的init方法將其初始化。
public static void init(Context context) { sRes = context.getResources(); }
切換夜間模式時,通過更新uiMode來更新Resources的配置,系統(tǒng)會根據(jù)其uiMode讀取對應night下的資源,同時在res中給夜間模式的資源添加-night后綴,比如values-night,drawable-night。
public static void updateNightMode(boolean on) { DisplayMetrics dm = sRes.getDisplayMetrics(); Configuration config = sRes.getConfiguration(); config.uiMode &= ~Configuration.UI_MODE_NIGHT_MASK; config.uiMode |= on ? Configuration.UI_MODE_NIGHT_YES : Configuration.UI_MODE_NIGHT_NO; sRes.updateConfiguration(config, dm); }
至于Android的資源讀取,我們可以參考老羅的博客《Android應用程序資源的查找過程》,分析看看資源是怎么被精準找到的。這種方法相對前兩種的好處就是資源添加非常簡單清晰,但是UI上的更新還是無法做到非常順滑的切換。
我是怎么找到第三種方案的?
在Android開發(fā)文檔中搜索night發(fā)現(xiàn)如下,可以通過UiModeManager來實現(xiàn)
night: Night time
notnight: Day time
Added in API level 8.
This can change during the life of your application if night mode is left in auto mode (default), in which case the mode changes based on the time of day. You can enable or disable this mode using UiModeManager. See Handling Runtime Changes for information about how this affects your application during runtime.
不幸的是必須在駕駛模式下才有效,那是不是打開駕駛模式再設置呢,實際上是不可行的,駕駛模式下系統(tǒng)UI有變動,這樣是不可取的。
/** * Sets the night mode. Changes to the night mode are only effective when * the car or desk mode is enabled on a device. * * The mode can be one of: * {@link #MODE_NIGHT_NO}- sets the device into notnight * mode. * {@link #MODE_NIGHT_YES} - sets the device into night mode. * {@link #MODE_NIGHT_AUTO} - automatic night/notnight switching * depending on the location and certain other sensors. */ public void setNightMode(int mode)
從源碼開始看起,UiModeManagerService.java的setNightMode方法中:
if (isDoingNightModeLocked() && mNightMode != mode) { Settings.Secure.putInt(getContext().getContentResolver(), Settings.Secure.UI_NIGHT_MODE, mode); mNightMode = mode; updateLocked(0, 0); } boolean isDoingNightModeLocked() { return mCarModeEnabled || mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED; }
在 isDoingNightModeLocked中判斷了DockState和mCardMode的狀態(tài),如果滿足條件實際上只修改了mNightMode的值,繼續(xù)跟蹤updateLocked方法,可以看到在updateConfigurationLocked中更新了Configuration的uiMode。
讓我們轉(zhuǎn)向Configuration的uiMode的描述:
/** * Bit mask of the ui mode. Currently there are two fields: * The {@link #UI_MODE_TYPE_MASK} bits define the overall ui mode of the * device. They may be one of {@link #UI_MODE_TYPE_UNDEFINED}, * {@link #UI_MODE_TYPE_NORMAL}, {@link #UI_MODE_TYPE_DESK}, * {@link #UI_MODE_TYPE_CAR}, {@link #UI_MODE_TYPE_TELEVISION}, * {@link #UI_MODE_TYPE_APPLIANCE}, or {@link #UI_MODE_TYPE_WATCH}. * * The {@link #UI_MODE_NIGHT_MASK} defines whether the screen * is in a special mode. They may be one of {@link #UI_MODE_NIGHT_UNDEFINED}, * {@link #UI_MODE_NIGHT_NO} or {@link #UI_MODE_NIGHT_YES}. */ public int uiMode;
uiMode為public可以直接設置,既然UiModeManager設置nightMode只改了Configuration的uiMode,那我們是不是可以直接改其uiMode呢?
實際上只需要上面一小段代碼就可以實現(xiàn)了,但如果不去查看UiModeManager的夜間模式的實現(xiàn),不會想到只需要更新Configuration的uiMode就可以了。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助。
相關(guān)文章
使用Android系統(tǒng)提供的DownloadManager來下載文件
本篇文章主要介紹了使用Android系統(tǒng)提供的DownloadManager來下載文件,可以將長時間的下載任務交給系統(tǒng),完全由系統(tǒng)管理,有需要的可以了解下。2016-11-11Android ServiceManager的啟動和工作原理
這篇文章主要介紹了Android ServiceManager的啟動和工作原理,幫助大家更好的理解和學習使用Android開發(fā),感興趣的朋友可以了解下2021-03-03Android 之BottomsheetDialogFragment仿抖音評論底部彈出對話框效果(實例代碼)
這篇文章主要介紹了Android 中之BottomsheetDialogFragment仿抖音評論底部彈出對話框效果,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04Android MenuItem 自定義長按事件的實現(xiàn)
這篇文章主要介紹了Android MenuItem 自定義長按事件的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08