在Fragment中使用Color.RED调用getResources().getColor()时触发Resources$NotFoundException的解决咨询
在Fragment中使用Color.RED调用getResources().getColor()时触发Resources$NotFoundException的解决咨询
看起来你踩了一个很常见的小坑——把直接颜色值和颜色资源ID搞混啦!我来给你捋清楚问题出在哪,以及怎么解决:
问题根源
你现在的getRoundedDrawable方法里,调用了getResources().getColor(colorResId),但这个方法的作用是根据资源ID(比如R.color.red)去读取res/values/colors.xml里定义的颜色值,而Color.RED本身已经是一个直接的颜色int值(就是报错里的0xffff0000),不是资源ID。系统把这个int当成资源ID去查找,自然找不到对应的资源,就抛出Resources$NotFoundException了。
最简单的解决方法:修改方法直接接受颜色int
直接调整getRoundedDrawable的参数逻辑,让它直接接收颜色int值,不用再通过getResources().getColor()转换:
private GradientDrawable getRoundedDrawable(int color) { GradientDrawable drawable = new GradientDrawable(); drawable.setColor(color); // 直接使用传入的颜色int drawable.setCornerRadius(24 * getResources().getDisplayMetrics().density); return drawable; }
调用的时候还是像你原来那样传Color.RED就行:
feedback.setBackground(getRoundedDrawable(Color.RED));
进阶方案:兼容资源ID和直接颜色值
如果你有时候需要用res里定义的颜色资源,有时候又想用Color.RED这类直接颜色值,可以给方法做个重载,写两个版本:
// 用于传入颜色资源ID的版本 private GradientDrawable getRoundedDrawableFromRes(int colorResId) { GradientDrawable drawable = new GradientDrawable(); // 建议用ContextCompat.getColor做版本兼容,API 23+也能正常用 drawable.setColor(ContextCompat.getColor(getContext(), colorResId)); drawable.setCornerRadius(24 * getResources().getDisplayMetrics().density); return drawable; } // 用于传入直接颜色int的版本 private GradientDrawable getRoundedDrawable(int color) { GradientDrawable drawable = new GradientDrawable(); drawable.setColor(color); drawable.setCornerRadius(24 * getResources().getDisplayMetrics().density); return drawable; }
之后根据需求调用就行:
- 用资源ID:
getRoundedDrawableFromRes(R.color.my_red) - 用直接颜色:
getRoundedDrawable(Color.RED)
额外小提示
另外要注意,getResources().getColor(int)这个方法在API 23之后就被废弃了,推荐用ContextCompat.getColor(Context context, int id),它会自动处理不同Android版本的兼容问题,不管是处理资源ID还是直接颜色值的场景,都更稳妥。
内容来源于stack exchange
相关产品推荐
相关产品推荐

