Android夜间模式最佳实践
由于Android的设置中并没有夜间模式的选项,对于喜欢睡前玩手机的用户,只能简单的调节手机屏幕亮度来改善体验。目前越来越多的应用开始把夜间模式加到自家应用中,没准不久google也会把这项功能添加到Android系统中吧。
业内关于夜间模式的实现,有两种主流方案,各有其利弊,我较为推崇第三种方案:
1、通过切换theme来实现夜间模式。
2、通过资源id映射的方式来实现夜间模式。
3、通过修改uiMode来切换夜间模式。
值得一提的是,上面提到的几种方案,都是资源内嵌在Apk中的方案,像新浪微博那种需要通过下载方式实现的夜间模式方案,网上有很多介绍,这里不去讨论。
下面简要描述下几种方案的实现原理:
一、通过切换theme来实现夜间模式
首先在attrs.xml中,为需要随theme变化的内容定义属性
<?xmlversion="1.0"encoding="utf-8"?> <resources> <attrname="textColor"format="color|reference"/> <attrname="mainBackground"format="color|reference"/> </resources>
其次在不同的theme中,对属性设置不同的值,在styles.xml中定义theme如下
<?xmlversion="1.0"encoding="utf-8"?> <resources> <!--默认--> <stylename="ThemeDefault"parent="Theme.AppCompat.Light.DarkActionBar"> <itemname="mainBackground">#ffffff</item> <itemname="textColor">#000000</item> </style> <!--夜间--> <stylename="ThemeNight"parent="Theme.AppCompat.Light.DarkActionBar"> <itemname="mainBackground">#000000</item> <itemname="textColor">#ffffff</item> </style> </resources>
在布局文件中使用对应的值,通过?attr/属性名,来获取不同theme对应的值。
<LinearLayoutxmlns: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中调用如下changeTheme方法,其中isNightMode为一个全局变量用来标记当前是否为夜间模式,在设置完theme后,还需要调用restartActivity或者setContentView重新刷新UI。
publicvoidchangeTheme(){
if(isNightMode){
setTheme(R.style.ThemeDefault);
isNightMode=false;
}else{
setTheme(R.style.ThemeNight);
isNightMode=true;
}
setContentView(R.layout.activity_main);
}
到此即完成了一个夜间模式的简单实现,包括Google自家在内的很多应用都是采用此种方式实现夜间模式的,这应该也是Android官方推荐的方式。
但这种方式有一些不足,规模较大的应用,需要随theme变化的属性会很多,都需要逐一定义,有点麻烦,另外一个缺点是要使得新theme生效,一般需要restartActivity来切换UI,会导致切换主题时界面闪烁。
不过也可以通过调用如下updateTheme方法,只更新需要更新的部分,规避闪烁问题,只是需要写上一堆updateTheme方法。
privatevoidupdateTheme(){
TypedValuetypedValue=newTypedValue();
Resources.Themetheme=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映射的方式实现夜间模式
通过id获取资源时,先将其转换为夜间模式对应id,再通过Resources来获取对应的资源。
publicstaticDrawablegetDrawable(Contextcontext,intid){
returncontext.getResources().getDrawable(getResId(id));
}
publicstaticintgetResId(intdefaultResId){
if(!isNightMode()){
returndefaultResId;
}
if(sResourceMap==null){
buildResourceMap();
}
intthemedResId=sResourceMap.get(defaultResId);
returnthemedResId==0?defaultResId:themedResId;
}
这里是通过HashMap将白天模式的resId和夜间模式的resId来一一对应起来的。
privatestaticvoidbuildResourceMap(){
sResourceMap=newSparseIntArray();
sResourceMap.put(R.drawable.common_background,R.drawable.common_background_night);
//...
}
这个方案简单粗暴,麻烦的地方和第一种方案一样:每次添加资源都需要建立映射关系,刷新UI的方式也与第一种方案类似,貌似今日头条,网易新闻客户端等主流新闻阅读应用都是通过这种方式实现的夜间模式。
三、通过修改uiMode来切换夜间模式
首先将获取资源的地方统一起来,使用Application对应的Resources,在Application的onCreate中调用ResourcesManager的init方法将其初始化。
publicstaticvoidinit(Contextcontext){
sRes=context.getResources();
}
切换夜间模式时,通过更新uiMode来更新Resources的配置,系统会根据其uiMode读取对应night下的资源,同时在res中给夜间模式的资源添加-night后缀,比如values-night,drawable-night。
publicstaticvoidupdateNightMode(booleanon){
DisplayMetricsdm=sRes.getDisplayMetrics();
Configurationconfig=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开发文档中搜索night发现如下,可以通过UiModeManager来实现
night:Nighttime
notnight:Daytime
AddedinAPIlevel8.
Thiscanchangeduringthelifeofyourapplicationifnightmodeisleftinautomode(default),inwhichcasethemodechangesbasedonthetimeofday.YoucanenableordisablethismodeusingUiModeManager.SeeHandlingRuntimeChangesforinformationabouthowthisaffectsyourapplicationduringruntime.
不幸的是必须在驾驶模式下才有效,那是不是打开驾驶模式再设置呢,实际上是不可行的,驾驶模式下系统UI有变动,这样是不可取的。
/**
*Setsthenightmode.Changestothenightmodeareonlyeffectivewhen
*thecarordeskmodeisenabledonadevice.
*
*Themodecanbeoneof:
*{@link#MODE_NIGHT_NO}-setsthedeviceintonotnight
*mode.
*{@link#MODE_NIGHT_YES}-setsthedeviceintonightmode.
*{@link#MODE_NIGHT_AUTO}-automaticnight/notnightswitching
*dependingonthelocationandcertainothersensors.
*/
publicvoidsetNightMode(intmode)
从源码开始看起,UiModeManagerService.java的setNightMode方法中:
if(isDoingNightModeLocked()&&mNightMode!=mode){
Settings.Secure.putInt(getContext().getContentResolver(),Settings.Secure.UI_NIGHT_MODE,mode);
mNightMode=mode;
updateLocked(0,0);
}
booleanisDoingNightModeLocked(){
returnmCarModeEnabled||mDockState!=Intent.EXTRA_DOCK_STATE_UNDOCKED;
}
在isDoingNightModeLocked中判断了DockState和mCardMode的状态,如果满足条件实际上只修改了mNightMode的值,继续跟踪updateLocked方法,可以看到在updateConfigurationLocked中更新了Configuration的uiMode。
让我们转向Configuration的uiMode的描述:
/**
*Bitmaskoftheuimode.Currentlytherearetwofields:
*
The{@link#UI_MODE_TYPE_MASK}bitsdefinetheoveralluimodeofthe
*device.Theymaybeoneof{@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}defineswhetherthescreen
*isinaspecialmode.Theymaybeoneof{@link#UI_MODE_NIGHT_UNDEFINED},
*{@link#UI_MODE_NIGHT_NO}or{@link#UI_MODE_NIGHT_YES}.
*/
publicintuiMode;
uiMode为public可以直接设置,既然UiModeManager设置nightMode只改了Configuration的uiMode,那我们是不是可以直接改其uiMode呢?
实际上只需要上面一小段代码就可以实现了,但如果不去查看UiModeManager的夜间模式的实现,不会想到只需要更新Configuration的uiMode就可以了。
以上就是本文的全部内容,希望对大家的学习有所帮助。