夜间模式方法之套一层蒙版

public class NightModeUtils {
	 public final static int THEME_SUN = 1;
	 public final static int THEME_NIGHT = 2;
//	 public final static boolean cheched = false;
//	 public static int getSwitchDayNightMode(Context context) {
//	        int mode = getDayNightMode(context);
//	        return mode == THEME_SUN ? THEME_NIGHT : THEME_SUN;
//	    }
//	 public static int getDayNightMode(Context context) {
//	        SharedPreferences sharedPreferences = getSharedPreferences(context);
//	        return sharedPreferences.getInt("SUN_NIGHT_MODE", THEME_SUN);
//	    }
//	 private static SharedPreferences getSharedPreferences(Context context) {
//	        return context.getSharedPreferences("NightModeDemo", Context.MODE_APPEND);
//	    }
	 public static void onActivityCreateSetTheme(Activity activity) {
		 boolean checked = (Boolean) SpUtils.get(activity, "night_day", true);
	        if (checked) {
	        	activity.setTheme(R.style.AppSunTheme);
			}else {
				activity.setTheme(R.style.AppNightTheme);
			}
	    }
}

上面是选择style中的两种模式的工具类

 
                

            
            
添加switch选择按钮布局

night_mode_switch = (UISwitchButton) view.findViewById(R.id.night_mode_switch_one);
		boolean checked = (Boolean) SpUtils.get(getActivity(), "night_day", true);
		night_mode_switch.setChecked(checked);
		night_mode_switch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					SpUtils.put(getActivity(), "night_day", true);
					Log.d("zhsy", "night==");
					night();
				} else {
					SpUtils.put(getActivity(), "night_day", false);
					Log.d("zhsy", "day==");
					day();
				}
			}
		});
对选择按钮控件的监听

	private void night() {
		if (mNightView == null) {
			mNightView = new TextView(getActivity());
			mNightView.setBackgroundColor(0xaa000000);
		}

		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);
		lp.gravity = Gravity.BOTTOM;
		lp.y = 10;
		try {
			mWindowManager.addView(mNightView, lp);
		} catch (Exception ex) {
		}
	}

	private void day() {
		try {
			mWindowManager.removeView(mNightView);
		} catch (Exception ex) {
		}
	}
通过WindowManager控制蒙版的添加和删除来模拟夜间和白天的模式

NightModeUtils.onActivityCreateSetTheme(getActivity());




在oncreate方法中调用控制切换主题的方法

你可能感兴趣的:(编程中问题解决方案)