将上下文传递到 getColor,Android Studio
Passing context into getColor, Android Studio
我一直在尝试使用自定义颜色设置按钮和其他项目。我是 java 的新手,我一直在努力学习如何正确使用上下文。我做了一些研究,但我仍然无法找到解决方案。
android 监视器错误是一个空指针异常,这是它有问题的代码行。
int buttonBackground = ContextCompat.getColor(this, R.color.buttonBackgrounds);
我在我的 class 中声明了这个变量,然后在一个方法中进一步向下,我这样写:
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);
阅读答案以了解上下文 getter 方法之间的区别 here。
可能会导致异常,您调用 getBaseContext()
,当它 returns null
,因此出现空指针异常。
当想要使用 activity 的上下文时(在 activity class 内),您可以通过 this
(或 YourActivityClass.this
,其中 YourActivityClass 始终是您的 activity 的名称)作为 Context
参数。所以有例外的行应该是这样的:
int buttonBackground = ContextCompat.getColor(this, R.color.buttonBackgrounds);
我一直在尝试使用自定义颜色设置按钮和其他项目。我是 java 的新手,我一直在努力学习如何正确使用上下文。我做了一些研究,但我仍然无法找到解决方案。
android 监视器错误是一个空指针异常,这是它有问题的代码行。
int buttonBackground = ContextCompat.getColor(this, R.color.buttonBackgrounds);
我在我的 class 中声明了这个变量,然后在一个方法中进一步向下,我这样写:
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);
阅读答案以了解上下文 getter 方法之间的区别 here。
可能会导致异常,您调用 getBaseContext()
,当它 returns null
,因此出现空指针异常。
当想要使用 activity 的上下文时(在 activity class 内),您可以通过 this
(或 YourActivityClass.this
,其中 YourActivityClass 始终是您的 activity 的名称)作为 Context
参数。所以有例外的行应该是这样的:
int buttonBackground = ContextCompat.getColor(this, R.color.buttonBackgrounds);