今天在友盟错误统计中发现一个小问题,NoSuchMethodError: android.content.Context.getDrawable这个错,
这个代码在源码中是可以看到的,但是在android 4.3手机上面会报错,具体错误信息和代码如下:
Drawable drawable = mContext.getDrawable(R.drawable.community_ques);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
CenterAlignImageSpan image = new CenterAlignImageSpan(drawable);
原因:Context类的getDrawable(res)/geColor(res)方法和Resources的getDrawable(res,theme)/getColor(res.theme)都是API21才添加的,低版本系统无法找到该方法所以报异常。
解决办法:
使用Resources的 getDrawable(res),但是该方法在API22已废弃。
使用 ContextCompat.getDrawable(context,res)。如:ContextCompat.getDrawable(MainActivity.this,R.drawable.radio_btn_background_show);
改成这样既可:
Drawable drawable1 = ContextCompat.getDrawable(mContext, R.drawable.community_essence);
drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
CenterAlignImageSpan image1 = new CenterAlignImageSpan(drawable1);