當下很多app都實現(xiàn)了夜間模式,其實個人感覺用著并不舒服,黑不溜秋的。不過總會有很多人想要這個需求,這不,最近也遇到了。于是上網(wǎng)搜了搜資料。這里簡單記錄下實現(xiàn)方法。

網(wǎng)上很多文章都講解了好幾種方案,不過總會有這樣那樣的問題,如車載模式之類的,有些有閃爍現(xiàn)象。所以這里我就用了下最麻煩的那種方案,通過定義attrs來實現(xiàn)的。
在網(wǎng)上看到了一個大神寫好的類,我也是直接拿過來用了 
聲明:這兩個類為網(wǎng)上拿過來的,這里就不貼了,需要的請下載Demo
這里面首先寫好界面,然后根據(jù)界面的控件來定義attrs
<?xml version="1.0" encoding="utf-8"?><resources> <attr name="btn_bg" format="color|reference"/> <attr name="ui_background" format="color|reference"/></resources>網(wǎng)上很多講解都說要再布局文件中寫background=”?attr/ui_background”,這樣寫確實很麻煩,很多布局都這樣寫應該很坑了吧。其實不用寫,直接在代碼里設置就行了。唯一麻煩的就是每個Activity里面都有進行夜間模式的切換。
值得注意的是,這個代碼要在values,values-v21里的styles都寫一遍,不然只能適配21以下或21以上之中的一種。
<!--白天主題--> <style name="DayTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="color代碼實現(xiàn)重要的地方都已經(jīng)標注出來了
{ super.onCreate(savedInstanceState); /** * 注意此處代碼寫到setContentView前面 */ mDayNightHelper = new DayNightHelper(this); if (mDayNightHelper.isDay()) { setTheme(R.style.DayTheme); } else { setTheme(R.style.NightTheme); } setContentView(R.layout.activity_main); mText = (TextView) findViewById(R.id.tv); mContainer = (LinearLayout) findViewById(R.id.activity_main); mToolBar = (Toolbar) findViewById(R.id.tool_bar); mToolBar.setTitle(""); setSupportActionBar(mToolBar); mSwitch = (Button) findViewById(R.id.btn_switch); mSwitch.setOnClickListener(this); if (mDayNightHelper.isDay()) { mText.setText("Day"); } else { mText.setText("Night"); } /** * 初始化的時候也要切換模式 */ switchMode(); }切換的時候直接調(diào)用這兩個方法就行了
不要忘記修改狀態(tài)欄
/** * 修改主題 */ private void changeTheme() { if (mDayNightHelper.isDay()) { mDayNightHelper.setMode(DayNight.NIGHT); setTheme(R.style.NightTheme); mText.setText("Night"); } else { mDayNightHelper.setMode(DayNight.DAY); setTheme(R.style.DayTheme); mText.setText("Day"); } } /** * 修改界面顏色 */ private void switchMode() { TypedValue bgContainer = new TypedValue(); TypedValue bgSwitch = new TypedValue(); TypedValue bgToolBar = new TypedValue(); Resources.Theme theme = getTheme(); theme.resolveAttribute(R.attr.btn_bg, bgSwitch, true); theme.resolveAttribute(R.attr.ui_background, bgContainer, true); theme.resolveAttribute(R.attr.colorPrimary, bgToolBar, true); mSwitch.setBackgroundResource(bgSwitch.resourceId); mContainer.setBackgroundResource(bgContainer.resourceId); mToolBar.setBackgroundResource(bgToolBar.resourceId); /** * 不可忘記 */ switchStatusBar(); } /** * switch statusBar */ private void switchStatusBar() { if (Build.VERSION.SDK_INT >= 21) { TypedValue primaryDark = new TypedValue(); Resources.Theme theme = getTheme(); theme.resolveAttribute(R.attr.colorPrimaryDark, primaryDark, true); getWindow().setStatusBarColor(getResources().getColor(primaryDark.resourceId)); } }新聞熱點
疑難解答