1. 程式人生 > >android 小功能之----修改狀態列藍色

android 小功能之----修改狀態列藍色

狀態列 即手機頂部顯示手機訊號 電量那一欄 如果你的activity頂部標題欄和狀態列無色差 你就不需要修改 一般情況下都會有這種情況 下面 我說一下如何修改狀態列的顏色

新建一個activity
建立一個通知欄 管理類 SystemBarTintManager 你可以修改它得狀態 如顏色 高度等

/**
* 通知欄管理類
*
*
*/

public class SystemBarTintManager {

static {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        try {
            Class c = Class.forName("android.os.SystemProperties");
            Method m = c.getDeclaredMethod("get", String.class);
            m.setAccessible(true);
            sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
        } catch (Throwable e) {
            sNavBarOverride = null;
        }
    }
}


/**
 * The default system bar tint color value.
 */
public static final int DEFAULT_TINT_COLOR = 0x99000000;

private static String sNavBarOverride;

private final SystemBarConfig mConfig;
private boolean mStatusBarAvailable;
private boolean mNavBarAvailable;
private boolean mStatusBarTintEnabled;
private boolean mNavBarTintEnabled;
private View mStatusBarTintView;
private View mNavBarTintView;

/**
 * Constructor. Call this in the host activity onCreate method after its
 * content view has been set. You should always create new instances when
 * the host activity is recreated.
 *
 * @param activity The host activity.
 */
@TargetApi(19)
public SystemBarTintManager(Activity activity) {

    Window win = activity.getWindow();
    ViewGroup decorViewGroup = (ViewGroup) win.getDecorView();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // check theme attrs
        int[] attrs = {android.R.attr.windowTranslucentStatus,
                android.R.attr.windowTranslucentNavigation};
        TypedArray a = activity.obtainStyledAttributes(attrs);
        try {
            mStatusBarAvailable = a.getBoolean(0, false);
            mNavBarAvailable = a.getBoolean(1, false);
        } finally {
            a.recycle();
        }

        // check window flags
        WindowManager.LayoutParams winParams = win.getAttributes();
        int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if ((winParams.flags & bits) != 0) {
            mStatusBarAvailable = true;
        }
        bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
        if ((winParams.flags & bits) != 0) {
            mNavBarAvailable = true;
        }
    }

    mConfig = new SystemBarConfig(activity, mStatusBarAvailable, mNavBarAvailable);
    // device might not have virtual navigation keys
    if (!mConfig.hasNavigtionBar()) {
        mNavBarAvailable = false;
    }

    if (mStatusBarAvailable) {
        setupStatusBarView(activity, decorViewGroup);
    }
    if (mNavBarAvailable) {
        setupNavBarView(activity, decorViewGroup);
    }

}

/**
 * Enable tinting of the system status bar.
 *
 * If the platform is running Jelly Bean or earlier, or translucent system
 * UI modes have not been enabled in either the theme or via window flags,
 * then this method does nothing.
 *
 * @param enabled True to enable tinting, false to disable it (default).
 */
public void setStatusBarTintEnabled(boolean enabled) {
    mStatusBarTintEnabled = enabled;
    if (mStatusBarAvailable) {
        mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
    }
}

/**
 * Enable tinting of the system navigation bar.
 *
 * If the platform does not have soft navigation keys, is running Jelly Bean
 * or earlier, or translucent system UI modes have not been enabled in either
 * the theme or via window flags, then this method does nothing.
 *
 * @param enabled True to enable tinting, false to disable it (default).
 */
public void setNavigationBarTintEnabled(boolean enabled) {
    mNavBarTintEnabled = enabled;
    if (mNavBarAvailable) {
        mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
    }
}

/**
 * Apply the specified color tint to all system UI bars.
 *
 * @param color The color of the background tint.
 */
public void setTintColor(int color) {
    setStatusBarTintColor(color);
    setNavigationBarTintColor(color);
}

/**
 * Apply the specified drawable or color resource to all system UI bars.
 *
 * @param res The identifier of the resource.
 */
public void setTintResource(int res) {
    setStatusBarTintResource(res);
    setNavigationBarTintResource(res);
}

/**
 * Apply the specified drawable to all system UI bars.
 *
 * @param drawable The drawable to use as the background, or null to remove it.
 */
public void setTintDrawable(Drawable drawable) {
    setStatusBarTintDrawable(drawable);
    setNavigationBarTintDrawable(drawable);
}

/**
 * Apply the specified alpha to all system UI bars.
 *
 * @param alpha The alpha to use
 */
public void setTintAlpha(float alpha) {
    setStatusBarAlpha(alpha);
    setNavigationBarAlpha(alpha);
}

/**
 * Apply the specified color tint to the system status bar.
 *
 * @param color The color of the background tint.
 */
public void setStatusBarTintColor(int color) {
    if (mStatusBarAvailable) {
        mStatusBarTintView.setBackgroundColor(color);
    }
}

/**
 * Apply the specified drawable or color resource to the system status bar.
 *
 * @param res The identifier of the resource.
 */
public void setStatusBarTintResource(int res) {
    if (mStatusBarAvailable) {
        mStatusBarTintView.setBackgroundResource(res);
    }
}

/**
 * Apply the specified drawable to the system status bar.
 *
 * @param drawable The drawable to use as the background, or null to remove it.
 */
@SuppressWarnings("deprecation")
public void setStatusBarTintDrawable(Drawable drawable) {
    if (mStatusBarAvailable) {
        mStatusBarTintView.setBackgroundDrawable(drawable);
    }
}

/**
 * Apply the specified alpha to the system status bar.
 *
 * @param alpha The alpha to use
 */
@TargetApi(11)
public void setStatusBarAlpha(float alpha) {
    if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mStatusBarTintView.setAlpha(alpha);
    }
}

/**
 * Apply the specified color tint to the system navigation bar.
 *
 * @param color The color of the background tint.
 */
public void setNavigationBarTintColor(int color) {
    if (mNavBarAvailable) {
        mNavBarTintView.setBackgroundColor(color);
    }
}

/**
 * Apply the specified drawable or color resource to the system navigation bar.
 *
 * @param res The identifier of the resource.
 */
public void setNavigationBarTintResource(int res) {
    if (mNavBarAvailable) {
        mNavBarTintView.setBackgroundResource(res);
    }
}

/**
 * Apply the specified drawable to the system navigation bar.
 *
 * @param drawable The drawable to use as the background, or null to remove it.
 */
@SuppressWarnings("deprecation")
public void setNavigationBarTintDrawable(Drawable drawable) {
    if (mNavBarAvailable) {
        mNavBarTintView.setBackgroundDrawable(drawable);
    }
}

/**
 * Apply the specified alpha to the system navigation bar.
 *
 * @param alpha The alpha to use
 */
@TargetApi(11)
public void setNavigationBarAlpha(float alpha) {
    if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mNavBarTintView.setAlpha(alpha);
    }
}

/**
 * Get the system bar configuration.
 *
 * @return The system bar configuration for the current device configuration.
 */
public SystemBarConfig getConfig() {
    return mConfig;
}

/**
 * Is tinting enabled for the system status bar?
 *
 * @return True if enabled, False otherwise.
 */
public boolean isStatusBarTintEnabled() {
    return mStatusBarTintEnabled;
}

/**
 * Is tinting enabled for the system navigation bar?
 *
 * @return True if enabled, False otherwise.
 */
public boolean isNavBarTintEnabled() {
    return mNavBarTintEnabled;
}

private void setupStatusBarView(Context context, ViewGroup decorViewGroup) {
    mStatusBarTintView = new View(context);
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight());
    params.gravity = Gravity.TOP;
    if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) {
        params.rightMargin = mConfig.getNavigationBarWidth();
    }
    mStatusBarTintView.setLayoutParams(params);
    mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
    mStatusBarTintView.setVisibility(View.GONE);
    decorViewGroup.addView(mStatusBarTintView);
}

private void setupNavBarView(Context context, ViewGroup decorViewGroup) {
    mNavBarTintView = new View(context);
    LayoutParams params;
    if (mConfig.isNavigationAtBottom()) {
        params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getNavigationBarHeight());
        params.gravity = Gravity.BOTTOM;
    } else {
        params = new LayoutParams(mConfig.getNavigationBarWidth(), LayoutParams.MATCH_PARENT);
        params.gravity = Gravity.RIGHT;
    }
    mNavBarTintView.setLayoutParams(params);
    mNavBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
    mNavBarTintView.setVisibility(View.GONE);
    decorViewGroup.addView(mNavBarTintView);
}

/**
 * Class which describes system bar sizing and other characteristics for the current
 * device configuration.
 *
 */
public static class SystemBarConfig {

    private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height";
    private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height";
    private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape";
    private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width";
    private static final String SHOW_NAV_BAR_RES_NAME = "config_showNavigationBar";

    private final boolean mTranslucentStatusBar;
    private final boolean mTranslucentNavBar;
    private final int mStatusBarHeight;
    private final int mActionBarHeight;
    private final boolean mHasNavigationBar;
    private final int mNavigationBarHeight;
    private final int mNavigationBarWidth;
    private final boolean mInPortrait;
    private final float mSmallestWidthDp;

    private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) {
        Resources res = activity.getResources();
        mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
        mSmallestWidthDp = getSmallestWidthDp(activity);
        mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME);
        mActionBarHeight = getActionBarHeight(activity);
        mNavigationBarHeight = getNavigationBarHeight(activity);
        mNavigationBarWidth = getNavigationBarWidth(activity);
        mHasNavigationBar = (mNavigationBarHeight > 0);
        mTranslucentStatusBar = translucentStatusBar;
        mTranslucentNavBar = traslucentNavBar;
    }

    @TargetApi(14)
    private int getActionBarHeight(Context context) {
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            TypedValue tv = new TypedValue();
            context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
            result = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
        }
        return result;
    }

    @TargetApi(14)
    private int getNavigationBarHeight(Context context) {
        Resources res = context.getResources();
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            if (hasNavBar(context)) {
                String key;
                if (mInPortrait) {
                    key = NAV_BAR_HEIGHT_RES_NAME;
                } else {
                    key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME;
                }
                return getInternalDimensionSize(res, key);
            }
        }
        return result;
    }

    @TargetApi(14)
    private int getNavigationBarWidth(Context context) {
        Resources res = context.getResources();
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            if (hasNavBar(context)) {
                return getInternalDimensionSize(res, NAV_BAR_WIDTH_RES_NAME);
            }
        }
        return result;
    }

    @TargetApi(14)
    private boolean hasNavBar(Context context) {
        Resources res = context.getResources();
        int resourceId = res.getIdentifier(SHOW_NAV_BAR_RES_NAME, "bool", "android");
        if (resourceId != 0) {
            boolean hasNav = res.getBoolean(resourceId);
            // check override flag (see static block)
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
            return hasNav;
        } else { // fallback
            return !ViewConfiguration.get(context).hasPermanentMenuKey();
        }
    }

    private int getInternalDimensionSize(Resources res, String key) {
        int result = 0;
        int resourceId = res.getIdentifier(key, "dimen", "android");
        if (resourceId > 0) {
            result = res.getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @SuppressLint("NewApi")
    private float getSmallestWidthDp(Activity activity) {
        DisplayMetrics metrics = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        } else {
            // TODO this is not correct, but we don't really care pre-kitkat
            activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        }
        float widthDp = metrics.widthPixels / metrics.density;
        float heightDp = metrics.heightPixels / metrics.density;
        return Math.min(widthDp, heightDp);
    }

    /**
     * Should a navigation bar appear at the bottom of the screen in the current
     * device configuration? A navigation bar may appear on the right side of
     * the screen in certain configurations.
     *
     * @return True if navigation should appear at the bottom of the screen, False otherwise.
     */
    public boolean isNavigationAtBottom() {
        return (mSmallestWidthDp >= 600 || mInPortrait);
    }

    /**
     * Get the height of the system status bar.
     *
     * @return The height of the status bar (in pixels).
     */
    public int getStatusBarHeight() {
        return mStatusBarHeight;
    }

    /**
     * Get the height of the action bar.
     *
     * @return The height of the action bar (in pixels).
     */
    public int getActionBarHeight() {
        return mActionBarHeight;
    }

    /**
     * Does this device have a system navigation bar?
     *
     * @return True if this device uses soft key navigation, False otherwise.
     */
    public boolean hasNavigtionBar() {
        return mHasNavigationBar;
    }

    /**
     * Get the height of the system navigation bar.
     *
     * @return The height of the navigation bar (in pixels). If the device does not have
     * soft navigation keys, this will always return 0.
     */
    public int getNavigationBarHeight() {
        return mNavigationBarHeight;
    }

    /**
     * Get the width of the system navigation bar when it is placed vertically on the screen.
     *
     * @return The nbsp;width of the navigation bar (in pixels). If the device does not have
     * soft navigation keys, this will always return 0.
     */
    public int getNavigationBarWidth() {
        return mNavigationBarWidth;
    }

    /**
     * Get the layout inset for any system UI that appears at the top of the screen.
     *
     * @param withActionBar True to include the height of the action bar, False otherwise.
     * @return The layout inset (in pixels).
     */
    public int getPixelInsetTop(boolean withActionBar) {
        return (mTranslucentStatusBar ? mStatusBarHeight : 0) + (withActionBar ? mActionBarHeight : 0);
    }

    /**
     * Get the layout inset for any system UI that appears at the bottom of the screen.
     *
     * @return The layout inset (in pixels).
     */
    public int getPixelInsetBottom() {
        if (mTranslucentNavBar && isNavigationAtBottom()) {
            return mNavigationBarHeight;
        } else {
            return 0;
        }
    }

    /**
     * Get the layout inset for any system UI that appears at the right of the screen.
     *
     * @return The layout inset (in pixels).
     */
    public int getPixelInsetRight() {
        if (mTranslucentNavBar && !isNavigationAtBottom()) {
            return mNavigationBarWidth;
        } else {
            return 0;
        }
    }

}

}

在你的activity 的oncreate();方法中呼叫
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setTranslucentStatus(true);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.colorbar);//通知欄所需顏色 請引用color檔案中的顏色
}
AppManager.getAppManager().addActivity(this);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
新建一個方法


private void setTranslucentStatus(boolean b) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (b) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
此時 還有一點很重要 狀態列的會覆蓋你的標題欄 解決它需要在你的activity的xml佈局檔案的最外層控制元件加兩行程式碼
android:fitsSystemWindows=”true”
android:clipToPadding=”true”
將狀態列和activity的標題欄分割開來

如需專案的所有activity都和狀態列同一顏色 個人建議你 建一個baseactivity 在他的oncreate()中 呼叫就好 只需要在你每個xml檔案中加上上面兩行程式碼就好
此時就大功告成了

相關推薦

android 功能----修改狀態藍色

狀態列 即手機頂部顯示手機訊號 電量那一欄 如果你的activity頂部標題欄和狀態列無色差 你就不需要修改 一般情況下都會有這種情況 下面 我說一下如何修改狀態列的顏色 新建一個activity 建立一個通知欄 管理類 SystemBarTintMan

Android最佳實踐SystemBar狀態全版本適配方案

前言 自從MD設計規範出來後,關於系統狀態列的適配越受到關注,因為MD在5.0以後把系統狀態列的顏色改為可由開發者配置的,而在5.0之前則無法指定狀態列的顏色,所以這篇就說說使用Toolbar對系統狀態列的適配策略 主流App的適配效果 手Q在這方面適

程式——動態修改狀態文字顏色/背景/動畫及頁面樣式

初次開發小程式,很多東西都是一邊百度一邊摸索學習,這幾天收穫還是很大的。 小程式API真的應該好好地去學習一遍吶,熟悉API的屬性,再百度各位前輩大佬的例子,那就很容易上手了。 現在又開始學習了,感覺很不錯,每天進步一點點也是好的。  .wxml: <vie

Android 修改狀態狀態列為view的圖片的一部分)①

Android 修改狀態列,讓狀態列和佈局中view的第一個圖片重合 效果圖如下: 這個效果完全可以用style來達到效果 下面是根據stysle來改動 在res下新建一個values-v19 新建styles.xml <?xml version="1.

Android實現修改狀態背景、字型和圖示顏色的方法

前言: Android開發,對於狀態列的修改,實在是不友好,沒什麼api可以用,不像ios那麼方便.但是ui又喜歡只搞ios一套.沒辦法.各種翻原始碼,寫反射.真的蛋疼. 需求場景: 當toolbar及狀態列需要為白色或淺色時(如簡書),狀態列由於用的Light風格Theme,字型,

Android開發應用狀態、導航欄都透明

  直接上程式碼 //狀態列、導航欄都透明 private void hideStatusBarNavigationBar() { if (Build.VERSION.SDK_INT = Build.VERSION_CODES.LOLLIPOP)

Android學習第八彈改變狀態的顏色使其與APP風格一體化

公眾號:smart_android 作者:耿廣龍|loonggg 點選“閱讀原文”,可檢視更多內容和乾貨 導語:沉浸式狀態列,改變狀態列的顏色使之與APP風格一體化是不是感覺很漂亮,很美?其實實現這種效果並不難,google在4.4及以下提供了相關的方法。 我

Android 修改狀態和沉浸式佈局總結

不多說獻上工具類。package com.yazhi1992.practice.immersion_status_bar; import android.app.Activity; import android.content.Context; import android

android系統修改狀態背景色以及文字顏色

修改狀態列的顏色一般是android系統5.1以上才支援,程式碼如下 activity.getWindow().setStatusBarColor(activity.getResources().getColor(R.color.custom_status_bar_c

Android改變狀態的顏色使其與APP風格一體化

導語:沉浸式狀態列,改變狀態列的顏色使之與APP風格一體化是不是感覺很漂亮,很美?其實實現這種效果並不難,google在4.4及以下提供了相關的方法。 我相信大家肯定看到過很多軟體有沉浸式狀態列,在執行該App時改變了手機螢幕頂部狀態列的顏色,使他們的風格非常的統一,看起來異常的漂亮和清爽。想不想實現這

Android修改狀態的背景顏色

一,概述 我相信很多初入Android開發的開發者都為自己開發的app的狀態列煩惱過,狀態列和自己的介面風格格格不入,但是不知道如何修改這個狀態列的顏色,感覺無從下手.我最近就是被這個狀態的預設風格搞得焦頭爛額,終於找到了相應的解決辦法.雖然程式碼不是我寫的,我也只能看懂一

Android修改狀態的顏色和我們App的風格一樣

就是自定義一個主題: <resources> <!-- Base application theme. --> <style name="AppTheme" parent="AppBaseTheme"> <!-- Customiz

Android修改狀態顏色

最近公司的專案,要求統一狀態列,做了之後在別的手機上都完美適配。但在華為mate10pro上卻成了介個樣子。試了好多種方法無果後,最終找到了以下介個工具類,有遇到相同問題的童鞋可以參考哦!public class StatusBarUtil {    public stati

Android隱藏狀態、設定全屏、取消全屏】

我將這三個設定程式碼寫在一個工具類當中,當你要對某個Activity呼叫這三個功能的時候,把Activity本身作為引數傳遞進去即可。 程式碼如下: <span style="font-fa

android沉浸式狀態、變色狀態、透明狀態修改狀態顏色及透明

首先我要區分清楚沉浸式狀態列與變色狀態列。 沉浸式狀態列指的是,狀態列隱藏,在手指做了相關操作後,狀態列顯示出來,例如視訊播放器,在播放視訊時是隱藏狀態列的,但是點選螢幕的時候,狀態列會顯示出來,再例如文字閱讀器,在閱讀的時候是全屏的,然後從螢幕上方下滑或者下

android隱藏狀態,全屏顯示和隱藏虛擬按鍵

廢話不多說,直接貼程式碼 //去除title requestWindowFeature(Window.FEATURE_NO_TITLE);   //去掉Activity上面的狀態列 getWindow().setFlags(WindowManager.La

android 修改狀態顏色

android狀態列顏色修改 狀態列顏色的修改在4.4和5.x環境下分別有不同的方式,低於4.4以下是不能修改的。 5.x環境下 方式一,狀態列將顯示為純淨的顏色,沒有漸變效果 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Android 五步修改狀態顏色

五步修改狀態列顏色 標籤(空格分隔): 狀態列顏色變化 Android開發一直以來對安卓系統的狀態列都不大滿意,在4.4以前只能選擇隱藏或者顯示,而不能夠改變其顏色以適應我們自己APP的整體風格。在安卓5.0釋出以後,介面實在美到爆,狀態列的顏色也可以自定義了。於是乎我

android技巧點擊兩次退出活動

code over ast finish int ide amp return ini 通常在主活動中可以設置連擊退出程序,下面通過代碼來實現這一功能: @Override//按兩次back鍵退出public boolean onKeyDown(int keyCode, K

微信程式物流狀態時間軸

一個月左右沒更新部落格了,最近有點懶了哈(工作上真的忙),很多工作上學習到的東西都沒有及時分享出來,有點愧疚,不過自己最近一直在收集資料和學習一些新技術,最主要是想要構建自己的前端技術體系和自定義一個前端規範文件,哈哈哈。說重點啦,微信小程式裡面開發的商城模組還挺多的,剛好寫了一個物流狀態的時間軸,簡單分享一