在Activity中或Fragment中任意改变状态栏的颜色

本文介绍了一种实现沉浸式UI的方法,包括通过代码调整状态栏颜色、使用反射机制获取状态栏高度等关键技术点,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        在公司要求弄出高大上的沉浸式模式时,查阅了好多资料,感觉都不怎么符合我的要求,只有一些比较重点的功能可以进行采集。以下直接进入正题。

        这里有3种机型的运行图,模拟机上的5.0-6.0的话可能比4.4的会有些差异,带了些半透明的阴影,但是我用真机测试时的并没有出现半透明的现象,话不多说我先贴上运行图上来:

这里写图片描述

        下面这3张图上是6.0的运行图:(注我的默认是黑色,可在style文件中的AppThem中进行设置)

这里写图片描述
6.0运行红色StatusBar图带阴影
这里写图片描述
华为真机6.0运行红色StatusBar图
这里写图片描述

  • 开始贴代码
**★styles.xml文件代码★**
<resources>

    <style name="AppTheme.Base" parent="Theme.AppCompat.Light">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="BaseAppTheme" parent="AppTheme.Base">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="BaseAppTheme"/>

</resources>
**★colors.xml文件代码★**
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#000</color>
    <color name="colorPrimaryDark">#000</color>
    <color name="colorAccent">#FF4081</color>
    <color name="base_color">#DE5C25</color>
</resources>
**★主布局文件代码★**(注:Fragment功能的改我已经注释,要想查看,可直接导入工程解开注释运行查看)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout"
    android:clipToPadding="true"
    android:fitsSystemWindows="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="true"
        android:fitsSystemWindows="true"
        android:visibility="gone" />

    <Button
        android:id="@+id/btn_red"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="红色"
        android:onClick="onClick"/>

    <Button
        android:id="@+id/btn_green"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="绿色"
        android:onClick="onClick" />

    <Button
        android:id="@+id/btn_blue"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="蓝色"
        android:onClick="onClick"/>

    <Button
        android:id="@+id/btn_orange"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="橙色"
        android:onClick="onClick"/>
    <Button
        android:id="@+id/btn_img"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="背景图片"
        android:onClick="onClick"/>
    <Button
        android:id="@+id/btn_nomor"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="恢复默认"
        android:onClick="onClick"/>

</LinearLayout>
**★Activity动态改变StatusBar颜色代码★**
package com.czb.statusbar;

import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czb.statusbar.fragment.BlueFragment;
import com.czb.statusbar.fragment.OrangFragment;
import com.czb.statusbar.fragment.RedFragment;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements OrangFragment.ListenerStatusColorOrange,BlueFragment.ListenerStatusColorBlue,RedFragment.ListenerStatusColorRed {

    private static final String TAG = MainActivity.class.getSimpleName();
    private ViewPager viewPager;
    private TextView textView;
    private ViewGroup view;
    private View rootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         //需要在4.4版本以上执行
        if (android.os.Build.VERSION.SDK_INT > 18) {
            Window window = getWindow();
//设置StatusBar为透明显示,需要在setContentView之前完成操作
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.activity_main);
        rootView = findViewById(R.id.layout);


        // 创建TextView用于叠加StatusBar的颜色块
        textView = new TextView(this);
        LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, getStatusBarHeight());
        textView.setBackgroundColor(Color.parseColor("#3F9FE0"));
        textView.setLayoutParams(lParams);
        // 获得根视图并把TextView加进去。
        view = (ViewGroup) getWindow().getDecorView();
        view.addView(textView);

        //inintPagerData();//此处是开启Fragment颜色替换的功能,我进行了注释

    }

    //初始化ViewPager
    private void inintPagerData() {
        viewPager = ((ViewPager) findViewById(R.id.viewPager));
        viewPager.setAdapter(new MyFragemtnPager(getSupportFragmentManager()));
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Log.e(TAG, "fragmenPosition:" + position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    // 通过反射机制获取手机状态栏高度
    public int getStatusBarHeight() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    @Override
    public void setStatusColor(String colorValue) {
        Log.e(TAG,"进来刷新蓝色");
        this.textView.setBackgroundColor(Color.parseColor(colorValue));

    }

    @Override
    public void setStatusOrangeColor(String colorValue) {
        Log.e(TAG,"进来刷新橙色");
       this.textView.setBackgroundColor(Color.parseColor(colorValue));
    }

    @Override
    public void setStatusRedColor(String colorValue) {
        Log.e(TAG,"进来刷新红色");
        this.textView.setBackgroundColor(Color.parseColor(colorValue));
    }

    public void onClick(View view) {
        String colorValue="#FFFFFF";
        boolean isNomor=false;//用于判断是否是恢复默认颜色
        switch (view.getId()){
            case R.id.btn_red:
                Log.e(TAG,"进来刷新红色");
                colorValue="#FF0000";
                this.textView.setBackgroundColor(Color.parseColor(colorValue));
                rootView.setBackgroundColor(Color.parseColor(colorValue));
                isNomor=false;
                break;
            case R.id.btn_green:
                Log.e(TAG,"进来刷新绿色");
                colorValue="#00FF00";
                this.textView.setBackgroundColor(Color.parseColor(colorValue));
                rootView.setBackgroundColor(Color.parseColor(colorValue));
                isNomor=false;
                break;
            case R.id.btn_blue:
                Log.e(TAG,"进来刷新蓝色");
                colorValue="#0000FF";
                this.textView.setBackgroundColor(Color.parseColor(colorValue));
                rootView.setBackgroundColor(Color.parseColor(colorValue));
                isNomor=false;
                break;
            case R.id.btn_orange:
                Log.e(TAG,"进来刷新橙色");
                colorValue="#DE5C25";
                this.textView.setBackgroundColor(Color.parseColor(colorValue));
                rootView.setBackgroundColor(Color.parseColor(colorValue));
                isNomor=false;
                break;
            case R.id.btn_nomor:
                colorValue="#00000000";
                this.textView.setBackgroundColor(Color.parseColor("#89000000"));
                rootView.setBackgroundColor(Color.parseColor(colorValue));
                isNomor=true;
                break;
            case R.id.btn_img:
                colorValue="#00000000";
                this.textView.setBackgroundColor(Color.parseColor(colorValue));
                rootView.setBackgroundResource(R.mipmap.timg);
                isNomor=false;
                break;
        }
      if (android.os.Build.VERSION.SDK_INT > 18){
            if(isNomor){
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }else{
                Window window = getWindow();
                window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
        }
    }


    class MyFragemtnPager extends FragmentPagerAdapter {

        private List<Fragment> fragmentList;

        public MyFragemtnPager(FragmentManager fm) {
            super(fm);
            fragmentList = new ArrayList<>();
            fragmentList.add(OrangFragment.getInstance());
            fragmentList.add(BlueFragment.getInstance());
            fragmentList.add(RedFragment.getInstance());
        }

        @Override
        public Fragment getItem(int position) {

            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }
    }
}

点击此处下载源代码文件

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值