jjzjj

android - PrimaryDark 未在 android 中设置 StatusBar 颜色

coder 2023-12-27 原文

我创建了一个应用程序,它有多个主题并且动态变化。我的意思是在运行时用户可以选择不同的主题。以便 UI 组件颜色在运行时发生变化。我陷入了一个奇怪的问题。问题是状态栏颜色没有根据主题改变。 statusBar 始终保持初始主题颜色。

values-v21/style.xml如下

    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/accent</item>
        <item name="android:textColorPrimary">@color/primary_text</item>
        <item name="android:icon">@color/icons</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>

values-v21/themes.xml is as below
===================================

<resources>    
    <style name="AppThemeRed" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">#F44336</item>
        <item name="colorPrimaryDark">#D32F2F</item>
        <item name="colorAccent">#FFCDD2</item>
        <item name="android:textColorPrimary">#FFFFFF</item>
        <item name="android:icon">@color/icons</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>

    <style name="AppThemeAmber" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">#FFC107</item>
        <item name="colorPrimaryDark">#FFA000</item>
        <item name="colorAccent">#FFEB3B</item>
        <item name="android:textColorPrimary">#FFFFFF</item>
        <item name="android:icon">@color/icons</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>

    <style name="AppThemeBlue" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">#3F51B5</item>
        <item name="colorPrimaryDark">#303F9F</item>
        <item name="colorAccent">#448AFF</item>
        <item name="android:textColorPrimary">#FFFFFF</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>

    <style name="AppThemePurple" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">#9C27B0</item>
        <item name="colorPrimaryDark">#7B1FA2</item>
        <item name="colorAccent">#7C4DFF</item>
        <item name="android:textColorPrimary">#FFFFFF</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>

    <style name="AppThemeYellow" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">#FFEB3B</item>
        <item name="colorPrimaryDark">#FBC02D</item>
        <item name="colorAccent">#CDDC39</item>
        <item name="android:textColorPrimary">#FFFFFF</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>
</resources>

当用户从主题选择对话框中选择一个主题时,我会调用一个函数并为该 Activity 设置主题,同时重新创建 Activity 。

public static void onActivityCreateSetTheme(Activity activity)
    {
        switch (sTheme)
        {
            case 0:
                activity.setTheme(R.style.AppThemeRed);
                break;

            case 1:
                activity.setTheme(R.style.AppThemeAmber);
                break;

            default:
            case 2:
                activity.setTheme(R.style.AppTheme);
                break;

            case 3:
                activity.setTheme(R.style.AppThemeBlue);
                break;

            case 4:
                activity.setTheme(R.style.AppThemePurple);
                break;

            case 5:
                activity.setTheme(R.style.AppThemeYellow);
                break;

        }
    }

我在抽屉中使用 NavigationView,抽屉位于状态栏下方没问题。但是状态栏没有选择当前主题的 primaryDark-color。它始终只采用默认主题(启动主题)颜色。

最佳答案

onCreate() 方法中通过 setTheme(int resId) 设置主题不会对 StatusBar 产生任何影响,因为它不是 Activity 本身的一部分AFAIK。

因此,为了达到预期的效果,您需要以编程方式进行。这是解析 R.attr.colorPrimaryDark 的 fragment ,如果 SDK 级别高于 21,则将其设置为 StatusBar:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    init();
    setContentView(R.layout.activity_management);
    // Further code
}

private void init(){
    // Set the Theme
    setTheme(R.style.MyAppTheme);
    if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
        getWindow().setStatusBarColor(getAttributeColor(R.attr.colorPrimaryDark));
    }
}

// Resolve the given attribute of the current theme
private int getAttributeColor(int resId) {
    TypedValue typedValue = new TypedValue();
    getTheme().resolveAttribute(resId, typedValue, true);
    int color = 0x000000;
    if (typedValue.type >= TypedValue.TYPE_FIRST_COLOR_INT && typedValue.type <= TypedValue.TYPE_LAST_COLOR_INT) {
        // resId is a color
        color = typedValue.data;
    } else {
        // resId is not a color
    }
    return color;
}

编辑

这种方法显然会覆盖通过 android:statusBarColor 设置的颜色。因此,如果您使用的是 NavigationDrawer 并且希望抽屉位于 StatusBar“下方”,则必须在抽屉打开后立即将 StatusBar 颜色手动设置为透明:

示例

actionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar,
            R.string.open_drawer_accessibility_desc,
            R.string.close_drawer_accessibility_desc) {

        @SuppressLint("NewApi")
        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            super.onDrawerSlide(drawerView, slideOffset);
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setStatusBarColor(
                        getResources().getColor(android.R.color.transparent));
            }
        }

        /** Called when a drawer has settled in a completely open state. */
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }

        /** Called when a drawer has settled in a completely closed state. */
        @Override
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
        }
    };
}

关于android - PrimaryDark 未在 android 中设置 StatusBar 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31137357/

有关android - PrimaryDark 未在 android 中设置 StatusBar 颜色的更多相关文章

  1. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  2. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  3. ruby 诅咒颜色 - 2

    如何使用Ruby的默认Curses库获取颜色?所以像这样:puts"\e[0m\e[30;47mtest\e[0m"效果很好。在浅灰色背景上呈现漂亮的黑色。但是这个:#!/usr/bin/envrubyrequire'curses'Curses.noecho#donotshowtypedkeysCurses.init_screenCurses.stdscr.keypad(true)#enablearrowkeys(forpageup/down)Curses.stdscr.nodelay=1Curses.clearCurses.setpos(0,0)Curses.addstr"Hello

  4. ruby - Rails 3 的 RGB 颜色选择器 - 2

    状态:我正在构建一个应用程序,其中需要一个可供用户选择颜色的字段,该字段将包含RGB颜色代码字符串。我已经测试了一个看起来很漂亮但效果不佳的。它是“挑剔的颜色”,并托管在此存储库中:https://github.com/Astorsoft/picky-color.在这里我打开一个关于它的一些问题的问题。问题:请建议我在Rails3应用程序中使用一些颜色选择器。 最佳答案 也许页面上的列表jQueryUIDevelopment:ColorPicker为您提供开箱即用的产品。原因是jQuery现在包含在Rails3应用程序中,因此使用基

  5. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  6. ruby-on-rails - 如何在 Rails 中设置路由的默认格式? - 2

    路由有如下代码:resources:orders,only:[:create],defaults:{format:'json'}resources:users,only:[:create,:update],defaults:{format:'json'}resources:delivery_types,only:[:index],defaults:{format:'json'}resources:time_corrections,only:[:index],defaults:{format:'json'}是否可以使用1个字符串为所有资源设置默认格式,每行不带“默认值”散列?谢谢。

  7. ruby-on-rails - environment.rb 中设置的常量在开发模式中消失 - 2

    了解Rails缓存如何工作的人可以真正帮助我。这是嵌套在Rails::Initializer.runblock中的代码:config.after_initializedoSomeClass.const_set'SOME_CONST','SOME_VAL'end现在,如果我运行script/server并发出请求,一切都很好。然而,在我的Rails应用程序的第二个请求中,一切都因单元化常量错误而变得糟糕。在生产模式下,我可以成功发出第二个请求,这意味着常量仍然存在。我已通过将以上内容更改为以下内容来解决问题:config.after_initializedorequire'some_cl

  8. ruby-on-rails - 如何在回形针 ruby​​ on rails 中设置默认图像 - 2

    最近我安装了Paperclipgem,我正在努力让默认图像在我的系统上工作,我将图像文件放在assets/images/pic.png中。这是我的模型User中的代码:has_attached_file:pic,:styles=>{:medium=>"300x300>",:thumb=>"100x100>"},:default_url=>'missing_:avatar.png'#:default_url=>'assets/images/avatar.png'has_attached_file:attach这是我的AddPicPaperClip迁移中的代码:defself.upadd_

  9. ruby-on-rails - Rails 中的类实例变量应该在互斥体中设置吗? - 2

    假设我的Rails项目中有一个设置实例变量的Ruby类。classSomethingdefself.objects@objects||=begin#somelogicthatbuildsanarray,whichisultimatelystoredin@objectsendendend是否可以多次设置@objects?是否有可能在一个请求期间,在上面的begin/end之间执行代码时,可以在第二个请求期间调用此方法?我想这实际上归结为Rails服务器实例如何fork的问题。我应该改用Mutex还是线程同步?例如:classSomethingdefself.objectsreturn@o

  10. ruby-on-rails - 如何在 ActionController::TestCase 请求中设置内容类型 - 2

    我试图像这样在我的测试用例中执行获取:request.env['CONTENT_TYPE']='application/json'get:index,:application_name=>"Heka"虽然,它失败了:ActionView::MissingTemplate:Missingtemplatealarm_events/indexwith{:handlers=>[:builder,:haml,:erb,:rjs,:rhtml,:rxml],:locale=>[:en,:en],:formats=>[:html]尽管在我的Controller中我有:respond_to:html,

随机推荐