在android中,夜间模式的切换


在android中,夜间模式其实很常见,在这里我们就简单的实现一下夜间模式的切换                             ~本人也是初入,但是基本上效果还可以

这里我先贴出来资源文件吧~

改变activity样式按钮!

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:id="@+id/ll"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:background="?containerBackground"  
    android:orientation="vertical" >  
  
    <Button  
        android:id="@+id/button"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:onClick="change"  
        android:text="改变Activity样式" />  
  
</LinearLayout>  
替换activity布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent" >  
  
    <ImageView  
        android:id="@+id/iv_fullImage"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent" />  
  
</RelativeLayout>  
values目录下资源文件attrs.xml
<?xml version="1.0" encoding="utf-8"?>  
<resources>  
  
    <attr name="containerBackground" format="reference|color"></attr>  
    <attr name="cardBackground" format="reference|color"></attr>  
    <attr name="imageSrc" format="reference|color"></attr>  
    <attr name="titleColor" format="reference|color"></attr>  
    <attr name="textColor" format="reference|color"></attr>  
    <attr name="selectorBtn" format="reference"></attr>  
    <attr name="selectorListItem" format="reference"></attr>  
  
</resources> 
colors.xml           颜色
<?xml version="1.0" encoding="utf-8"?>  
<resources>  
  
    <color name="white">#fafafa</color>  
    <color name="white_dark">#f3f3f3</color>  
    <color name="gray_light">#cccccc</color>  
    <color name="gray">#777</color>  
    <color name="gray_dark">#383838</color>  
    <color name="green_light">#8e9ea4</color>  
    <color name="green">#34515c</color>  
    <color name="green_dark">#1e3e4a</color>  
    <color name="night_mask">#90000000</color>  
  
</resources>  
styles.xml           activity的夜间和白天俩种样式
<resources xmlns:android="http://schemas.android.com/apk/res/android">  
  
    <!-- Application theme. -->  
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"></style>  
    <!-- 日间模式 -->  
    <style name="AppTheme_day" parent="AppTheme">  
        <item name="containerBackground">@color/white_dark</item>  
        <item name="titleColor">@color/gray_dark</item>  
        <item name="textColor">@color/gray</item>  
    </style>  
    <!-- 夜间模式 -->  
    <style name="AppTheme_night" parent="AppTheme">  
        <item name="containerBackground">@color/green_dark</item>  
        <item name="titleColor">@color/white_dark</item>  
        <item name="textColor">@color/green_light</item>  
   </style>  
  
    <style name="Theme.AppStartLoadTranslucent" parent="android:Theme">  
        <item name="android:windowIsTranslucent">true</item>  
        <item name="android:windowNoTitle">true</item>  
    </style>  
  
</resources>  

代码书写:(这里我会写另一个activity来显示效果,改变该工程的所有页面)

--------------MyApplication------------//设置全局的变量

import android.app.Application;  
import android.content.Context;  
  
public class MyApplication extends Application {  
    public static boolean isNeightMode = false;  
    public static Context mContext;  
  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        mContext = this.getApplicationContext();  
    }  
  
    public static Context getContext() {  
        return mContext;  
    }  
  
    public static void setNeightMode(boolean mode) {  
        isNeightMode = mode;  
    }  
}  

--------------BaseActivity---------------//作为所有activity的父类,改变主题样式

import android.annotation.SuppressLint;  
import android.app.Activity;  
import android.content.Context;  
import android.graphics.Bitmap;  
import android.graphics.PixelFormat;  
import android.graphics.drawable.BitmapDrawable;  
import android.graphics.drawable.Drawable;  
import android.os.Bundle;  
import android.os.Handler;  
import android.view.Menu;  
import android.view.View;  
import android.view.WindowManager;  
import android.view.WindowManager.LayoutParams;  
import android.widget.Toast;  
  
public class BaseActivity extends Activity {  
  
    private WindowManager mWindowManager;  
    private boolean mIsAddedView;  
    private LayoutParams mNightViewParam;  
    private View mNightView;  
  
    @SuppressLint("NewApi")  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        // 根据当前的主题类型设置对应的主题,放到onCreate方法之前  
        if (MyApplication.isNeightMode)  
            setTheme(R.style.AppTheme_night);  
        else  
            setTheme(R.style.AppTheme_day);  
        super.onCreate(savedInstanceState);  
        mIsAddedView = false;  
        if (MyApplication.isNeightMode) {  
            initNightView();  
            // 设置windowManage背景图的颜色  
            mNightView.setBackgroundResource(R.color.night_mask);  
        }  
  
    }  
  
    /** 
     * 初始化夜间模式的灰层 
     */  
    private void initNightView() {  
        if (mIsAddedView == true)  
            return;  
        mNightViewParam = new LayoutParams(LayoutParams.TYPE_APPLICATION,  
                LayoutParams.FLAG_NOT_TOUCHABLE  
                        | LayoutParams.FLAG_NOT_FOCUSABLE,  
                PixelFormat.TRANSPARENT);  
        mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);  
        mNightView = new View(this);  
        mWindowManager.addView(mNightView, mNightViewParam);  
        mIsAddedView = true;  
    }  
  
    public void ChangeToDay() {  
        MyApplication.setNeightMode(false);  
        Toast.makeText(this, "白天", 0).show();  
        mNightView.setBackgroundResource(android.R.color.transparent);  
    }  
  
    public void ChangeToNight() {  
        Toast.makeText(this, "黑天", 0).show();  
        MyApplication.setNeightMode(true);  
        if (mIsAddedView != true) {  
            initNightView();  
            mIsAddedView = true;  
        }  
        mNightView.setBackgroundResource(R.color.night_mask);  
    }  
  
    /** 
     * 改变当前日夜模式 
     */  
    @SuppressLint("NewApi")  
    public void changeViewMode() {  
        // 判断当前模式,如果是白天模式,改成夜间,如果是夜间模式,改成白天  
        boolean isNight = MyApplication.isNeightMode;  
        if (isNight)  
            ChangeToDay();  
        else  
            ChangeToNight();  
//      // 重新创建Activity  
//      recreate();  
    }  
    @Override  
    protected void onDestroy() {  
        if (mIsAddedView) {  
            mWindowManager.removeViewImmediate(mNightView);  
            mWindowManager = null;  
            mNightView = null;  
        }  
        super.onDestroy();  
    }  
}  

----------------ActivityCollection----------------//作为存储activity的工具类,在本身activity中添加!!!


import java.util.ArrayList;  
import java.util.List;  
  
import android.annotation.SuppressLint;  
import android.app.Activity;  
  
  
public class ActivityCollection {  
    private final static List<Activity> activityList = new ArrayList<Activity>();  
  
    public static List<Activity> getList() {  
        return activityList;  
    }  
  
    public static void addActivity(Activity activity) {  
        activityList.add(activity);  
    }  
  
    public static void removeActivity(Activity activity) {  
        activityList.remove(activity);  
    }  
  
    public static void finishAll() {  
        for (Activity activity : activityList) {  
            if (!activity.isFinishing()) {  
                activity.finish();  
            }  
        }  
        activityList.clear();  
    }  
  
    public static int getLeftSize() {  
        return activityList.size();  
    }  
  <pre name="code" class="java">import android.app.Activity;  
import android.graphics.Bitmap;  
import android.graphics.Rect;  
import android.view.View;  
  
public class UIUtils {  
    public static Bitmap captureContent(Activity activity) {  
        // View是你需要截图的View  
        View view = activity.getWindow().getDecorView();  
        view.setDrawingCacheEnabled(true);  
        view.buildDrawingCache();  
        Bitmap b1 = view.getDrawingCache();  
        // 获取状态栏高度 /  
        Rect frame = new Rect();  
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
        int statusBarHeight = frame.top;  
        // 获取屏幕长和高  
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();  
        int height = activity.getWindowManager().getDefaultDisplay()  
                .getHeight();  
        // 去掉标题栏  
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height  
                - statusBarHeight);  
        view.destroyDrawingCache();  
        return b;  
    }  
  
    /** 
     * 截屏 
     *  
     * @param activity 
     * @return 
     */  
//    MemCacheHelper.getInstance().put(KEY_SCREEN_CAPTURE, UIUtils.captureContent(this));  
    public static Bitmap captureScreen(Activity activity) {  
        activity.getWindow().getDecorView().setDrawingCacheEnabled(true);  
        Bitmap bmp = activity.getWindow().getDecorView().getDrawingCache();  
        return bmp;  
    }  
}  

@SuppressLint("NewApi") public static void refreshAllActivity() { for (Activity activity : activityList) { // 重新创建Activity activity.recreate(); // activity.overridePendingTransition(android.R.anim.fade_in, // android.R.anim.fade_out); } } }
 
   

//在一定程度上,切换时出现黑屏等现象,这里我们会做一个截屏操作来覆盖当前的activity来做一个假象,防止出现黑屏现象


---------------UIUils-------------------截屏相关类

import android.app.Activity;  
import android.graphics.Bitmap;  
import android.graphics.Rect;  
import android.view.View;  
  
public class UIUtils {  
    public static Bitmap captureContent(Activity activity) {  
        // View是你需要截图的View  
        View view = activity.getWindow().getDecorView();  
        view.setDrawingCacheEnabled(true);  
        view.buildDrawingCache();  
        Bitmap b1 = view.getDrawingCache();  
        // 获取状态栏高度 /  
        Rect frame = new Rect();  
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
        int statusBarHeight = frame.top;  
        // 获取屏幕长和高  
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();  
        int height = activity.getWindowManager().getDefaultDisplay()  
                .getHeight();  
        // 去掉标题栏  
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height  
                - statusBarHeight);  
        view.destroyDrawingCache();  
        return b;  
    }  
  
    /** 
     * 截屏 
     *  
     * @param activity 
     * @return 
     */  
//    MemCacheHelper.getInstance().put(KEY_SCREEN_CAPTURE, UIUtils.captureContent(this));  
    public static Bitmap captureScreen(Activity activity) {  
        activity.getWindow().getDecorView().setDrawingCacheEnabled(true);  
        Bitmap bmp = activity.getWindow().getDecorView().getDrawingCache();  
        return bmp;  
    }  
}  

-----------CaptureActivity----------------

import android.app.Activity;  
import android.content.Context;  
import android.content.Intent;  
import android.graphics.Bitmap;  
import android.os.Bundle;  
import android.os.Handler;  
import android.os.Message;  
import android.widget.ImageView;  
  
public class CaptureActivity extends Activity {  
    private static final String PARAM_MEM_CACHE_KEY = "PARAM_MEM_CACHE_KEY";  
    private static final int MSG_CLOSE_ACTIVITY = 1;  
    private String mCacheKey;  
  
    private Handler closeHandler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            super.handleMessage(msg);  
            if (msg.what == MSG_CLOSE_ACTIVITY) {  
                finish();  
                overridePendingTransition(android.R.anim.fade_in,  
                        android.R.anim.fade_out);  
                // 清除map集合中存储的屏幕截图  
                MemCacheHelper.getInstance().remove(mCacheKey);  
            }  
        }  
    };  
  
    public static void start(Context context, String memCacheKey) {  
        Intent starter = new Intent(context, CaptureActivity.class);  
        starter.putExtra(PARAM_MEM_CACHE_KEY, memCacheKey);  
        context.startActivity(starter);  
    }  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_capture);  
        // 获取刚才的屏幕截图  
        mCacheKey = getIntent().getStringExtra(PARAM_MEM_CACHE_KEY);  
        Bitmap bitmap = MemCacheHelper.getInstance().get(mCacheKey);  
        if (bitmap == null)  
            return;  
        // 找控件,设置背景图  
        final ImageView imageView = (ImageView) findViewById(R.id.iv_fullImage);  
        imageView.setImageBitmap(bitmap);  
  
        new Handler().postDelayed(new Runnable() {  
            public void run() {  
                // 重新创建所有的Activity  
                ActivityCollection.refreshAllActivity();  
                closeHandler.sendEmptyMessageDelayed(MSG_CLOSE_ACTIVITY, 300);  
            }  
        }, 100);  
    }  
}  

--------------------MemCacheHelper -----------------

import java.util.HashMap;  
  
public class MemCacheHelper {  
    private static final MemCacheHelper single = new MemCacheHelper();  
    /** 
     * 全局通用的临时缓存变量 使用方式,key是包名+变量名,value是引用类型,值类型请包装比如int-》Integer 
     */  
    public HashMap<String, Object> mTempVariable = new HashMap<String, Object>();  
  
    public static MemCacheHelper getInstance() {  
        return single;  
    }  
  
    /** 
     * 存储一个临时变量 
     *  
     * @param key 
     * @param value 
     */  
    public void put(String key, Object value) {  
        mTempVariable.put(key, value);  
    }  
  
    /** 
     * 获取一个临时变量 
     *  
     * @param key 
     * @return 
     */  
    public <T> T get(String key) {  
        return (T) mTempVariable.get(key);  
    }  
  
    /** 
     * 删除临时变量 
     *  
     * @param key 
     */  
    public void remove(String key) {  
        mTempVariable.remove(key);  
    }  
}  

----------------MainActivity----------------------//作为主程序代码  当然要最后来体现了   嘿嘿~~

public class MainActivity extends BaseActivity {  
  
    private static final String KEY_SCREEN_CAPTURE = "haha";  
  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        //将该activity添加到activity集合中  
        ActivityCollection.addActivity(this);  
    }  
  
    public void change(View v) {  
        // 截图并将图片存储到hashMap中  
        MemCacheHelper.getInstance().put(KEY_SCREEN_CAPTURE,  
                UIUtils.captureContent(this));  
        // 改变当前模式  
        changeViewMode();  
        // CaptureActivity.start(this, KEY_SCREEN_CAPTURE);  
        //做为假象截屏替换黑屏  
        Intent starter = new Intent(this, CaptureActivity.class);  
        starter.putExtra("PARAM_MEM_CACHE_KEY", KEY_SCREEN_CAPTURE);  
        overridePendingTransition(android.R.anim.fade_in,  
                android.R.anim.fade_out);  
        startActivity(starter);  
    }  
  
}  

-----------------OtherActivity-----------------------------//为了展示效果 而补充的另一个页面  这个不作为以上的工程项目中,上面的代码其实已经完成了切换功能。(这里教大家如何在别的activity中显示夜间效果----{添加到activity集合})

import android.os.Bundle;  
import android.view.View;  
  
//相同  其他页面也是同样继承Baseactivity  
public class OtherActivity extends BaseActivity{  
      
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        // TODO Auto-generated method stub  
        super.onCreate(savedInstanceState);  
          
        setContentView(R.layout.login_activity);  
          
        //相同 这里也是将该activity添加到集合中  
        ActivityCollection.addActivity(this);  
        /** 
         * 这里就可以显示夜间模式了~~~     一句话 只要添加入集合就可以啦 
         */  
    }  
}  

demo在这里就完工了,大家可以试试效果,当然夜间模式中,字的颜色和夜间模式相应的图片  还要等大家来写,这里就不做演示了

                                                                                                      ---------------------------仅供参考














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值