在Android 10(API 29)升级后,setColor方法可能无法正常工作的解决方法是使用setBackgroundColor方法替代。下面是一个示例代码:
// 获取要设置颜色的View
View view = findViewById(R.id.view);
// 在Android 10(API 29)及更高版本中,使用setBackgroundColor方法
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
view.setBackgroundColor(getResources().getColor(R.color.colorPrimary, null));
}
// 在Android 10(API 29)以下版本中,使用setColor方法
else {
view.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
在这个示例代码中,首先通过findViewById获取要设置颜色的View。然后,根据设备的API版本,使用不同的方法设置背景颜色。在Android 10及更高版本中,使用setBackgroundColor方法,并传入getColor方法获取的颜色值。在Android 10以下版本中,使用setColor方法,并传入getColor方法获取的颜色值。
请确保在res/values/colors.xml文件中定义了颜色资源,例如:
#FF4081
在这个示例中,colorPrimary是一个自定义的颜色资源,你可以根据自己的需求修改。