java - 将上下文传递给 getColor,Android Studio

标签 java android nullpointerexception android-context

我一直在尝试使用自定义颜色设置按钮和其他项目。我是 java 的新手,我一直在努力学习如何正确使用上下文。我做了一些研究,但仍然无法找到解决方案。

android 监视器错误是一个空指针异常,这是它有问题的代码行。

int buttonBackground = ContextCompat.getColor(this, R.color.buttonBackgrounds);

我在我的类中声明了这个变量,然后在一个方法中进一步向下,我这样写:

percussionButton.setBackgroundColor(buttonBackground);
instrumentButton.setBackgroundResource(android.R.drawable.btn_default);

我认为这两者可能会发生冲突,但我能想到的就这些。

如果之前有人回答过这个问题,我深表歉意,到目前为止,我无法从我找到的任何内容中获得答案。

我之前尝试过的事情:

int buttonBackground = ContextCompat.getColor(getBaseContext(), R.color.buttonBackgrounds);

int buttonBackground = ContextCompat.getColor(getApplicationContext(), R.color.buttonBackgrounds);

最佳答案

阅读答案以了解上下文获取方法之间的区别 here .
可能是这个异常引起的,你调用getBaseContext(),当它返回null时,因此出现空指针异常。
当想使用 Activity 的上下文(在 Activity 类中),您可以传递 this(或 YourActivityClass.this,其中 YourActivityClass 始终是您的 Activity 的名称)作为 上下文 参数。所以有异常(exception)的行应该是这样的:

int buttonBackground = ContextCompat.getColor(this, R.color.buttonBackgrounds);

关于java - 将上下文传递给 getColor,Android Studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41903144/

相关文章:

java - 通过原始套接字编码字符串 - 额外字符

java - 在单独的连续行中打印 3 个 JAVA 程序的输出,共享同一控制台,在多处理场景中使用\r

android - 我需要一个稳定且统一的解决方案来在 Android 和 IOS 网络浏览器中流式传输音频

android - 使用 volley 发送 firebase 推送通知

java - 在 ArrayList 中查找一个数字

java - XSD 中的模式验证是否不同?

java - 如何仅更改图像按钮内的图像而不是整个图像按钮

android - 即使在 gradle 中添加支持和设计后,如何让 Android TabLayout 工作?

java - NullPointerException 通过 Java 三元运算符的自动装箱行为

java - 返回数组的一个索引的方法会抛出 NullPointer