Android 夜间模式主题风格切换

1. 跟进源码 1.1 String.xml
Settings 模块

"夜间模式" "夜间模式会将您的屏幕色调调节为琥珀色,让您在光线昏暗的环境下可以更舒适地查看屏幕或阅读文字,并可能有助于您入睡。" "排定时间" "状态" "自动开启" "永不" "自定义时间安排" "日落到日出" "开始时间" "结束时间" "关闭。%1$s" "一律不自动开启。" "将在%1$s自动开启。" "将在日落时自动开启。" "开启。%1$s" "一律不自动关闭。" "将在%1$s自动关闭。" "将在日出时自动关闭。"

1.2 布局文件
Settings 模块 display_settings.xml,设置入口

1.3 逻辑控制
UiModeManager.setNightMode(value); 进行夜间模式和白天模式的切换
package com.android.settings; public class DisplaySettings extends SettingsPreferenceFragment implements Preference.OnPreferenceChangeListener, Indexable {@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Activity activity = getActivity(); final ContentResolver resolver = activity.getContentResolver(); addPreferencesFromResource(R.xml.display_settings); mNightModePreference = (ListPreference) findPreference(KEY_NIGHT_MODE); if (mNightModePreference != null) { final UiModeManager uiManager = (UiModeManager) getSystemService( Context.UI_MODE_SERVICE); final int currentNightMode = uiManager.getNightMode(); mNightModePreference.setValue(String.valueOf(currentNightMode)); mNightModePreference.setOnPreferenceChangeListener(this); } ... import android.app.UiModeManager; if (preference == mNightModePreference) { try { final int value = https://www.it610.com/article/Integer.parseInt((String) objValue); final UiModeManager uiManager = (UiModeManager) getSystemService( Context.UI_MODE_SERVICE); uiManager.setNightMode(value); } catch (NumberFormatException e) { Log.e(TAG,"could not persist night mode setting", e); } }

2.Demo 1.原理 【Android 夜间模式主题风格切换】调用UiModeManager夜间模式接口 + value-night资源文件
2.实现逻辑
public class MainActivity extends Activity {//实现Android白天/夜间模式的关键类 private UiModeManager mUiModeManager = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mUiModeManager = (UiModeManager) getSystemService(Context.UI_MODE_SERVICE); }public void night(View view) { mUiModeManager.setNightMode(UiModeManager.MODE_NIGHT_YES); }public void day(View view) { mUiModeManager.setNightMode(UiModeManager.MODE_NIGHT_NO); }

3.布局文件

4.夜间模式和白天模式的资源文件 values-night
#3B5125 #30E333 #FF4081 #000000

5.运行结果 Android 夜间模式主题风格切换
文章图片

Android 夜间模式主题风格切换
文章图片

    推荐阅读