我一直在尝试使用自定义颜色设置按钮和其他项目。我是 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/