android - 更改操作栏的颜色在 ICS 中不起作用

标签 android android-actionbar

我正在使用以下代码更改操作栏的颜色。

            actionBar= getSupportActionBar();
            actionBar.setBackgroundDrawable(new ColorDrawable(backgroundColor));

这在 onCreate() 方法中非常有效(即当我的 Activity 开始时)。

但是当我在 Android 4.1 中使用相同的代码在 onClick() 方法中更改操作栏的颜色时(即当用户点击按钮时),它会将操作栏的颜色更改为“白色”只是 backgroundColor 的值。

Android 2.3 中,无论是从 onCreate 还是 onClick() 调用,它在这两种情况下都工作得很好。

这对我来说似乎是死胡同。

最佳答案

似乎对于 Android 4.0Android 4.1(4.2 可以),一旦 Activity 开始,您就无法更改操作栏背景。

所以我想在这些情况下的解决方案是使用不同的背景颜色重新启动 Activity。

不是很优雅,但这是我能想到的最好的了。

也许是这样的:

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

    setContentView(R.layout.activity_main);
    Button btn = (Button) findViewById(R.id.btn);

    if (getIntent().hasExtra("color")) {
      getSupportActionBar().setBackgroundDrawable(
          new ColorDrawable(getIntent().getIntExtra("color", 0)));
    }

    btn.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {

        Intent it = getIntent();
        it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        it.putExtra("color", Color.BLUE);
        startActivity(it);

      }
    });
  }

关于android - 更改操作栏的颜色在 ICS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21958157/

相关文章:

android - 为什么在没有 setDisplayHomeAsUpEnabled() 的情况下出现向上按钮?

Android Studio 日历选择器

android - ActionBar MenuItem 分隔符

c# - 如何在 Xamarin android 中更改操作栏标题颜色

android - 如何在 TabLayout 中获取 Tab 的 View ?

android - 堆叠的 ActionBar 选项卡栏未填充父级

android - 操作栏在状态栏后面

android - 将 child 添加到 NavigationView 组内的 MenuItem

android - 更改处于选中状态的 EditText 控件的颜色

android - 在 OnItemClick 之后在 ListView 中显示来自数据库的游标结果