【问题标题】:Change ActionBar Background Color in code from Navigation List从导航列表更改代码中的 ActionBar 背景颜色
【发布时间】:2012-07-31 00:20:19
【问题描述】:

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

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

@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;
    }

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


第二次点击导航列表中的itemPosition 1,没有问题。


谁能告诉我这是为什么以及如何解决这个问题?感谢您的帮助!

【问题讨论】:

  • 你解决过这个问题吗?

标签: android android-actionbar


【解决方案1】:

尝试使用此代码:

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

【讨论】:

  • 这与原发帖人要求的基本相同,只是选择颜色的方式略有不同。它无法解决问题。
  • 我以前用过这个,它可以工作。将其更改为使用 Tykin 提到的十六进制方法完全符合问题所述。也许有人可以提供一些关于为什么 Tykin 的方法不适用于这种情况的见解。
  • 这行得通。我刚刚将 0x 更改为 # 并且效果很好,知道为什么吗?
  • @JMint 文档声明“支持的格式为:#RRGGBB #AARRGGBB 'red', 'blue' ...” 如果它正在寻找 int,您将使用 0x作为参数(例如使用方法public static int rgb (int red, int green, int blue))。查看developer.android.com/reference/android/graphics/Color.html了解更多信息。
【解决方案2】:

试试这个:

myActivity.invalidateOptionsMenu();

【讨论】:

    【解决方案3】:

    我也遇到了同样的问题。

    适用于 Visual Studio 等中的 Xamarin 用户。

    请在活动类中的 SetContentView(Resource.Layou......) 之后粘贴此内容。

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

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

    谢谢,希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2015-08-14
      • 2015-11-15
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 2014-03-05
      相关资源
      最近更新 更多