Android 从导航列表更改代码中的 ActionBar 背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11770512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:47:56  来源:igfitidea点击:

Change ActionBar Background Color in code from Navigation List

androidandroid-actionbar

提问by Tykin

I want to change the color of the Action Bar background when the user chooses a selection in the Navigation List.

当用户在导航列表中选择一个选项时,我想更改操作栏背景的颜色。

Currently, my code looks like this:

目前,我的代码如下所示:

@Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        ColorDrawable colorDrawable = new ColorDrawable();
        ActionBar actionBar = getActionBar();
        if(itemPosition == 0)
        {
            colorDrawable.setColor(0xffFEBB31);
            actionBar.setBackgroundDrawable(colorDrawable);
            return true;
        }
        if(itemPosition == 1)
        {
            colorDrawable.setColor(0xff9ACC00);
            actionBar.setBackgroundDrawable(colorDrawable);
            return true;
        }
        return false;
    }

However, the first time I select itemPosition 1 in the Navigation List, it changes the ActionBar color to white.

但是,当我第一次在导航列表中选择 itemPosition 1 时,它会将 ActionBar 颜色更改为白色。

enter image description here
The second time I click the itemPosition 1 in the Navigation List, I have no issue.

在此处输入图片说明
第二次单击导航列表中的 itemPosition 1 时,我没有问题。

enter image description here
Could anyone tell me why this is and how I can fix the problem? Thank you for the help!

在此处输入图片说明
谁能告诉我这是为什么以及如何解决这个问题?感谢您的帮助!

回答by Trevor

Try using this code:

尝试使用此代码:

ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#ffFEBB31"));
actionBar.setBackgroundDrawable(colorDrawable); 

回答by user2426991

Try this:

尝试这个:

myActivity.invalidateOptionsMenu();

回答by Momodu Deen Swarray

I was having this same problem.

我遇到了同样的问题。

For Xamarin Users in Visual Studio or the like.

对于 Visual Studio 等中的 Xamarin 用户。

Please paste this just after the SetContentView(Resource.Layou...... in the activity class.

请将其粘贴在活动类中的 SetContentView(Resource.Layou......) 之后。

// Setting ActionBar (Toolbar) background color natively var actionBar = this.ActionBar; actionBar.SetBackgroundDrawable(new ColorDrawable(Color.Black));

// Setting ActionBar (Toolbar) background color natively var actionBar = this.ActionBar; actionBar.SetBackgroundDrawable(new ColorDrawable(Color.Black));

You may change it as you deem necessary of do more on the actionBar variable.

您可以根据需要对 actionBar 变量进行更多更改。

Thanks hope this helps.

谢谢希望这会有所帮助。