Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 日夜模式切換實作詳解

編輯:關於 Android 程式設計

夜間模式的核心想法並不是去換主題、重建 Activity,而是在最上層疊一層半透明的遮罩,把整個畫面的亮度壓下來。這種做法改動小、效能好,也不會打斷使用者目前的操作狀態。

實作上需要三個零件:WindowManager 用來把遮罩 View 掛到視窗層級、SharedPreferences 用來記住使用者上次的選擇、一個開關按鈕負責在兩種狀態間切換。

一、主要程式碼

package org.david.dayandnightdemo.cor;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

    private WindowManager mWindowManager;
    private View myView;
    private Button btn_dayAndnight;
    private SharedPreferences skinSp;
    private final static String DAY = "day";
    private final static String NIGHT = "night";
    private int flage = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        skinSp = this.getSharedPreferences("skinchange", Context.MODE_PRIVATE);
        btn_dayAndnight = (Button) findViewById(R.id.btn_dayAndnight);
        btn_dayAndnight.setOnClickListener(this);

        // 上次選擇的狀態決定這次開啟時的樣子
        String mode = skinSp.getString("skin", "");
        if (mode != null || !mode.equals("")) {
            if (mode.equals(NIGHT)) {
                night();
            } else {
                day();
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (flage % 2 == 0) {
            night();
            btn_dayAndnight.setText("白天模式");
            btn_dayAndnight.setTextColor(Color.WHITE);
            flage++;
        } else {
            day();
            btn_dayAndnight.setText("夜間模式");
            btn_dayAndnight.setTextColor(Color.BLACK);
            flage++;
        }
    }

    public void night() {
        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.BOTTOM;
        params.y = 10;
        if (myView == null) {
            myView = new TextView(this);
            myView.setBackgroundColor(0x80000000);
        }
        mWindowManager.addView(myView, params);
        Editor edit = skinSp.edit();
        edit.putString("skin", NIGHT);
        edit.commit();
    }

    public void day() {
        if (myView != null) {
            mWindowManager.removeView(myView);
            Editor edit = skinSp.edit();
            edit.putString("skin", DAY);
            edit.commit();
        }
    }

    public void removeSkin() {
        if (myView != null) {
            mWindowManager.removeView(myView);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String mode = skinSp.getString("skin", "");
        if (mode.equals(NIGHT)) {
            removeSkin();
        }
    }
}

關鍵參數說明

0x80000000 是半透明黑,前面兩個十六進位數字是 alpha 通道。數值越大畫面越暗,實務上落在 0x60~0xA0 之間視覺比較舒服。

FLAG_NOT_TOUCHABLE | FLAG_NOT_FOCUSABLE 這兩個旗標非常重要:它讓這層遮罩「看得到但摸不到」,觸控事件會直接穿透到下面的介面,同時也不會搶走輸入焦點。少了它們,使用者會發現整個 App 突然點不動了。

onDestroy() 中的 removeSkin() 是必須的收尾。View 一旦透過 WindowManager.addView() 掛上去,就不再由 Activity 的版面樹管理,如果 Activity 銷毀時沒有手動移除,極可能造成視窗洩漏(WindowLeaked)的錯誤。

二、版面檔

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btn_dayAndnight"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn_changeskin" />

</RelativeLayout>

延伸思考

遮罩法的優點是簡單,缺點是它只壓暗畫面、並不改變配色,而且遮罩會蓋在 Dialog 與 Toast 之下。若要更完整的夜間體驗,通常會改用 setTheme() 更換主題並呼叫 recreate() 重建 Activity,或者透過 Resource 限定符(例如 -night)搭配 AppCompatDelegate.setDefaultNightMode() 讓系統自動切換資源。這兩種做法比較正規,但改造成本也相對高。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved