如何使用 Java 文件中的 R.Color 在 Android Studio 中更改操作栏 setBackgrounddrawable 颜色?

Uma*_*has 2 java android background colors r.java-file

我想在 Android Studio 中使用 Java 代码更改操作栏的颜色,

我有颜色代码的 color.xml 文件

android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getColor(R.color.colorVelocity)));   **//<<Error NullPointerException**
Run Code Online (Sandbox Code Playgroud)

告诉我如何解决这个问题,因为我想使用 R.color 我不想使用 color.parsecolor ("#hexcolor");

Chr*_*ard 5

这是一个空指针异常问题。我不确定你从哪里调用 getSupportActionBar() (这会给我更多关于为什么的上下文)但是你应该总是在调用它时检查 null 。因此,将您的代码更改为...

android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
  actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorVelocity))); 
}
Run Code Online (Sandbox Code Playgroud)

[编辑]

如果您不想使用已弃用的 getResources().getColor() 方法,请改用此方法...

android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
  actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, R.color.colorVelocity)));
}
Run Code Online (Sandbox Code Playgroud)

  • 操作栏对象运行良好,但 setBackgroundDrawable(new ColorDrawable(getColor(R.color.colorVelocity))); 不管用 (3认同)