为什么getDrawable()不能在某些Android设备上运行?

时间:2015-05-15 19:04:27

标签: android android-drawable

我正在接受" nosuchmethod error"在一些用户的手机上(例如摩托罗拉Razr i),但它在我的HTC上工作正常。以下是代码。

Drawable rBlack;
rBlack = getResources().getDrawable(R.drawable.rblack, getTheme());

Stacktrace:

java.lang.NoSuchMethodError: android.content.res.Resources.getDrawable
at org.petero.droidfish.myClass.onCreate(myClass.java:434)
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:803)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:619)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)

如果我使用此代码:

flipButton.setImageDrawable(getDrawable(R.drawable.rblack));

我收到此错误

java.lang.NoSuchMethodError: org.myclass.getDrawable
at org.myclass.onCreate(myclass.java:435)
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:803)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:619)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:42)

我打赌它在API中添加的getDrawable(R.drawable.rblack, getTheme());失败了。将该行更改为:

if(android.os.Build.VERSION.SDK_INT >= 21){
    rBlack = getResources().getDrawable(R.drawable.rblack, getTheme());
} else {
    rBlack = getResources().getDrawable(R.drawable.rblack);
}

答案 1 :(得分:28)

ContextCompat.getDrawable(Context context, int id)

答案 2 :(得分:1)

尝试添加以下代码行:

context.getResources().getDrawable(R.drawable.your_image_name);