首页 > 其他分享 >android-夜间模式

android-夜间模式

时间:2023-06-02 21:34:11浏览次数:46  
标签:夜间 activity 模式 UI MODE NIGHT android Configuration public


资源

1

Android Material Design系列之夜间模式 阐述了夜间模式的资源文件,告知建立了values-night文件夹

对于夜间模式的颜色和主题配置,我们需要建立一个res下建立一个values-night文件夹,里面放着夜间主题样式的color等资源。
colors.xml配置如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#0a0a0a</color>
    <color name="colorPrimaryDark">#000000</color>
    <color name="colorAccent">#fc0404</color>
    <color name="add_bg_color">#FF2ECC71</color>
    <color name="add_selected_color">#51C332</color>
    <color name="white">#ffffff</color>
    <color name="text_color">#7f7f7f</color>
    <color name="navigation_bar_color">#0a0a0a</color>
    <color name="color_control_normal">#f305be</color>
    <color name="text_color_primary">#00ffff</color>
    <color name="navigationview_bg_color">#000000</color>
</resources>

切换主体

isNight = sp.getBoolean("night", false);
if (isNight) {
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    sp.edit().putBoolean("night", false).commit();
} else {
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    sp.edit().putBoolean("night", true).commit();
}
recreate();

2. 夜间模式工具类

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.preference.PreferenceManager;

import java.lang.ref.WeakReference;

/**
 * Night Mode Helper
 * <p>
 * Helps use utilise the night and notnight resource qualifiers without being in car or dock mode.
 * <p>
 * Implementation is simple. Add the follow line at the top of your activity's onCreate just after
 * the super.onCreate(); The idea here is to do it before we create any views. So the new views will
 * use the correct Configuration.
 * 
 * <pre>
 * mNightModeHelper = new NightModeHelper(this, R.style.AppTheme);
 * </pre>
 * 
 * You can now use your instance of NightModeHelper to control which mode you are in. You can choose
 * to persist the current setting and hand it back to this class as the defaultUiMode, otherwise
 * this is done for you automatically.
 * <p>
 * I'd suggest you setup your Theme as follows:
 * <ul>
 * <li><b>res\values\styles.xml</b>
 * 
 * <pre>
 * <style name="AppTheme" parent="AppBaseTheme"></style>
 * </pre>
 * 
 * </li>
 * <li><b>res\values-night\styles.xml</b>
 * 
 * <pre>
 * <style name="AppBaseTheme" parent="@android:style/Theme.Holo"></style>
 * </pre>
 * 
 * </li>
 * <li><b>res\values-notnight\styles.xml</b>
 * 
 * <pre>
 * <style name="AppBaseTheme" parent="@android:style/Theme.Holo.Light"></style>
 * </pre>
 * 
 * </li>
 * </ul>
 * 
 * @author Simon Lightfoot <[email protected]>
 */
public class NightModeHelper {
    private static final String PREF_KEY = "nightModeState";

    private static int sUiNightMode = Configuration.UI_MODE_NIGHT_UNDEFINED;

    private WeakReference<Activity> mActivity;
    private SharedPreferences mPrefs;

    /**
     * Default behaviour is to automatically save the setting and restore it.
     */
    public NightModeHelper(Activity activity, int theme) {
        int currentMode = (activity.getResources().getConfiguration().uiMode
                & Configuration.UI_MODE_NIGHT_MASK);
        mPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
        init(activity, theme, mPrefs.getInt(PREF_KEY, currentMode));
    }

    /**
     * If you don't want the autoSave feature and instead want to provide your own persisted storage
     * for the mode, use the defaultUiMode for it.
     */
    public NightModeHelper(Activity activity, int theme, int defaultUiMode) {
        init(activity, theme, defaultUiMode);
    }

    public static int getUiNightMode() {
        return sUiNightMode;
    }

    private void init(Activity activity, int theme, int defaultUiMode) {
        mActivity = new WeakReference<Activity>(activity);
        if (sUiNightMode == Configuration.UI_MODE_NIGHT_UNDEFINED) {
            sUiNightMode = defaultUiMode;
        }
        updateConfig(sUiNightMode);

        // This may seem pointless but it forces the Theme to be reloaded
        // with new styles that would change due to new Configuration.
        activity.setTheme(theme);
    }

    private void updateConfig(int uiNightMode) {
        Activity activity = mActivity.get();
        if (activity == null) {
            throw new IllegalStateException("Activity went away?");
        }
        Configuration newConfig = new Configuration(activity.getResources().getConfiguration());
        newConfig.uiMode &= ~Configuration.UI_MODE_NIGHT_MASK;
        newConfig.uiMode |= uiNightMode;
        activity.getResources().updateConfiguration(newConfig, null);
        sUiNightMode = uiNightMode;
        if (mPrefs != null) {
            mPrefs.edit()
                    .putInt(PREF_KEY, sUiNightMode)
                    .apply();
        }
    }

    public void toggle() {
        if (sUiNightMode == Configuration.UI_MODE_NIGHT_YES) {
            notNight();
        } else {
            night();
        }
    }

    public void notNight() {
        updateConfig(Configuration.UI_MODE_NIGHT_NO);
        mActivity.get().recreate();
    }

    public void night() {
        updateConfig(Configuration.UI_MODE_NIGHT_YES);
        mActivity.get().recreate();
    }
}

3.Android Support Library 之 夜间模式

Android Support Library 之 夜间模式

4.android夜间模式浅析

android夜间模式浅析

  1. 定义DayNight主体,以及相关属性
<style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
      <!-- Customize your theme here. -->
      <item name="colorPrimary">@color/colorPrimary</item>
      <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
      <item name="colorAccent">@color/colorAccent</item>
</style>
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="colorPrimary">#3F51B5</color>
   <color name="colorPrimaryDark">#303F9F</color>
   <color name="colorAccent">#FF4081</color>
</resources>
  1. 在res下面创建values-night文件夹,创建colors.xml声明color属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="colorPrimary">#1f2023</color>
   <color name="colorPrimaryDark">#18181a</color>
   <color name="colorAccent">#FF4081</color>
</resources>
  1. 为程序设置初始模式
MODE_NIGHT_NO. 使用亮色(light)主题

MODE_NIGHT_YES. 使用暗色(dark)主题

MODE_NIGHT_AUTO. 根据当前时间自动切换 亮色(light)/暗色(dark)主题

MODE_NIGHT_FOLLOW_SYSTEM(默认选项). 设置为跟随系统,通常为 MODE_NIGHT_NO
  1. 在Application中进行初始化
public class MyApplication extends Application {
	static {
	    AppCompatDelegate.setDefaultNightMode(
	            AppCompatDelegate.MODE_NIGHT_NO);
	}
	
	@Override
	public void onCreate() {
	    super.onCreate();
	}

}
  1. 在初始化就切换夜间模式
public class MyApplication extends Application {
static {
    AppCompatDelegate.setDefaultNightMode(
            AppCompatDelegate.MODE_NIGHT_NO);
}

@Override
public void onCreate() {
    super.onCreate();
}

}
  1. 获取当前主体的状态
int currentNightMode = getResources().getConfiguration().uiMode
    & Configuration.UI_MODE_NIGHT_MASK;

case Configuration.UI_MODE_NIGHT_NO:

case Configuration.UI_MODE_NIGHT_YES:

case Configuration.UI_MODE_NIGHT_UNDEFINED:
  1. 通过主体确定
int currentNightMode = getResources().getConfiguration().uiMode
            & Configuration.UI_MODE_NIGHT_MASK;
    switch (currentNightMode) {
        case Configuration.UI_MODE_NIGHT_NO:
            getDelegate().setDefaultNightMode(
                    AppCompatDelegate.MODE_NIGHT_YES);


            break;
        case Configuration.UI_MODE_NIGHT_YES:
             getDelegate().setDefaultNightMode(
                AppCompatDelegate.MODE_NIGHT_NO);
            break;
        case Configuration.UI_MODE_NIGHT_UNDEFINED:
            getDelegate().setDefaultNightMode(
                    AppCompatDelegate.MODE_NIGHT_AUTO);
            break;
    }
    // 调用 recreate() 使设置生效
    recreate();
}
  1. 图片文件夹
    drawable-night


标签:夜间,activity,模式,UI,MODE,NIGHT,android,Configuration,public
From: https://blog.51cto.com/u_11797608/6405125

相关文章

  • 移动开发之设计模式-组合模式(IOS&Android)
    组合模式组合模式(CompositePattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。这种模式创建了一个包含自己对象组的类。该类提供了修改相......
  • Fragment原理解析androidx版本&ViewPager与Fragment
    资料Fragment生命周期为什么要通过Fragment.setArguments(Bundle)传递参数单独问题:动态方式,静态方式添加随Activity启动动态添加回退栈onSaveInstance静态方式添加FragmentmHost是这个finalFragmentControllermFragments=FragmentController.createController(newHostCallb......
  • java单例模式几种实现方式
    1、饿汉式(线程安全,调用效率高,但是不能延时加载):publicclassImageLoader{privatestaticImageLoaderinstance=newImageLoader;privateImageLoader(){}publicstaticImageLoadergetInstance(){returninstance;}}一上来就把单例对象创建出来了,要用的时候直......
  • Sentinel规则Pull模式持久化
    阅读文本大概需要3分钟。   前一篇【使用Nacos存储Sentinel的限流规则】讲了基于Nacos的Push模式持久化,这里讲下基于本地文件的Pull模式持久化。在网上看到一篇讲这个讲得不错的:从官网的说明https://github.com/alibaba/Sentinel/wiki/在生产环境中使用-Sentinel#Pull模式有......
  • 2014.4.25.12.51_context_2014.4.25_Android种的Context详解
    Android中Context详解----你所不知道的Context一、Context相关类的继承关系2二、什么时候创建Context实例5从上可知一下三点,即:1、它描述的是一个应用程序环境的信息,即上下文。2、该类是一个抽象(abstractclass)类,Android提供了该抽象类的具体实现类(后面我们会讲到是Co......
  • 2015.4.24.17.23_界面_2015.4.24__Android界面设计工具_0.01
    iOS,Android原型图设计软件–>AxureRP,UIDesigner,Pencil,iPhoneMockup,Justinmind<–#AxureRPAxureRP-快速原型制作软件–线框图,原型,规格文档,由美国AxureSoftwareSolutions,Inc.公司开发。AxureRP也分商业版和免费版,英文官方:http://www.axure.com/download中文网站:h......
  • android基础-ConstraintLayout
    资料约束布局ConstraintLayout看这一篇就够了ConstraintLayout布局居中|居右实现。ConstraintLayout中TextView文字超过屏幕问题ConstraintLayoutConstraintLayout字体超出屏幕解决方法约束布局ConstraintLayout看这一篇就够了具体的方法layout_constraintLeft_toLeftOflayout_c......
  • Android利用tcpdump抓包
    [b]Instructions[/b][url]http://source.android.com/porting/tcpdump.html[/url][b]SourceCodeandDocuments[/b][url]http://www.tcpdump.org/[/url][b]CompiledBinaryDownload[/b][url]http://www.strazzere.com/android/tcpdump[/url]......
  • android: workaround for slow ‘building workspace’ problem in eclipse
    Whiledevelopingforandroidoneclipse3.6ihadtheproblemthateachtimeisavedafile,eclipseblockedmeseveralsecondswith‘buildingworkspace…’.Similartothese:stackoverflow–android-compilation-is-slow-using-eclipsestackoverflow–android-......
  • Android通过 SharedPreference 实现用户名与密码的存储与调用
    注:Android实验课(一)的内容一、实验原理1.1实验目标编程实现用户名与密码的存储与调用。1.2实验要求设计用户登录界面、登录成功界面、用户注册界面,用户注册时,将其用户名、密码保存到SharedPreference中,登录时输入用户名、密码,读取SharedPreference,读取不到该用户名提示用户不存在,用......