package com.example.day_nigth;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private WindowManager mWindowManger;
// 设置夜间模式
private SharedPreferences skinSp;
private final static String DAY = "day";
private final static String NIGHT = "night";
private boolean isDay;
private View myView;
private ImageView imageView_night;
private TextView text_night;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
**//窗口管理者**
mWindowManger = (WindowManager) getSystemService(WINDOW_SERVICE);
imageView_night = (ImageView) findViewById(R.id.image_night);
text_night = (TextView) findViewById(R.id.text);
imageView_night.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (isDay) {
night();
imageView_night
.setImageResource(R.drawable.dayicon_leftdrawer_normal_night);
text_night.setText("日间");
} else {
day();
imageView_night
.setImageResource(R.drawable.nighticon_leftdrawer_normal);
text_night.setText("夜间");
}
isDay = !isDay;
skinSp.edit().putBoolean("isDay", isDay).commit();
}
});
init();
}
public void next(View v) {
startActivity(new Intent(this, SecondActivity.class));
}
// 日间夜间模式切换
private void init() {
skinSp = getSharedPreferences("skinchange", MODE_PRIVATE);
String mode = skinSp.getString("skin", "");
if (mode != null || !mode.equals("")) {
if (mode.equals(NIGHT)) {
night();
isDay = false;
} else {
day();
isDay = true;
}
}
}
@SuppressLint("ResourceAsColor")
private void night() {
@SuppressWarnings("deprecation")
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
LayoutParams.TYPE_APPLICATION,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER;
// params.y = 10;
if (myView == null) {
myView = new View(this);
myView.setBackgroundColor(0x80000000);
}
mWindowManger.addView(myView, params);
Editor edit = skinSp.edit();
edit.putString(“skin”, NIGHT);
edit.commit();
}
private void day() {
if (myView != null) {
mWindowManger.removeView(myView);
Editor edit = skinSp.edit();
edit.putString("skin", DAY);
edit.commit();
}
}
@Override
public void onDestroy() {
super.onDestroy();
String mode = skinSp.getString("skin", "");
if (mode.equals(NIGHT)) {
removeSkin();
}
}
public void removeSkin() {
if (myView != null) {
mWindowManger.removeView(myView);
}
}
}