来自数字字符串的 setBackgroundResource 导致致命错误 - Android/Java

setBackgroundResource from numeric string causes Fatal Error - Android/Java

我正在尝试从数字文件名(它必须是数字 - 这不能更改)字符串(图像是 1170.png)设置布局的背景。

我尝试使用以下示例:

Android drawables : Is there any way to somehow link the int IDs to the R drawable IDs?

然而,当我这样做时,结果如下:

06-03 08:36:47.551: E/AndroidRuntime(1765): FATAL EXCEPTION: main
06-03 08:36:47.551: E/AndroidRuntime(1765): Process: com.app.example, PID: 1765
06-03 08:36:47.551: E/AndroidRuntime(1765): android.content.res.Resources$NotFoundException: Resource ID #0x8c5
06-03 08:36:47.551: E/AndroidRuntime(1765):     at android.content.res.Resources.getValue(Resources.java:1123)
06-03 08:36:47.551: E/AndroidRuntime(1765):     at android.content.res.Resources.getDrawable(Resources.java:698)
06-03 08:36:47.551: E/AndroidRuntime(1765):     at android.view.View.setBackgroundResource(View.java:15303)
06-03 08:36:47.551: E/AndroidRuntime(1765):     at com.app.example.MainActivity.handleMessage(MainActivity.java:163)
06-03 08:36:47.551: E/AndroidRuntime(1765):     at com.app.example.ServiceManager$IncomingHandler.handleMessage(ServiceManager.java:28)
06-03 08:36:47.551: E/AndroidRuntime(1765):     at android.os.Handler.dispatchMessage(Handler.java:102)
06-03 08:36:47.551: E/AndroidRuntime(1765):     at android.os.Looper.loop(Looper.java:136)
06-03 08:36:47.551: E/AndroidRuntime(1765):     at android.app.ActivityThread.main(ActivityThread.java:5001)
06-03 08:36:47.551: E/AndroidRuntime(1765):     at java.lang.reflect.Method.invokeNative(Native Method)
06-03 08:36:47.551: E/AndroidRuntime(1765):     at java.lang.reflect.Method.invoke(Method.java:515)
06-03 08:36:47.551: E/AndroidRuntime(1765):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
06-03 08:36:47.551: E/AndroidRuntime(1765):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
06-03 08:36:47.551: E/AndroidRuntime(1765):     at dalvik.system.NativeStart.main(Native Method)

我的代码片段如下 - 它似乎是正确的 - 但它似乎有问题(很明显)。在这种情况下,任何人都可以发现我做错了什么吗?

String SnapShotFrame_TblTriviaLU = "1170";
RelativeLayout relativeLayout2 = (RelativeLayout) findViewById(R.id.gameplayLayout);
            int resId = getResources().getIdentifier(SnapShotFrame_TblTriviaLU, "drawable", getPackageName());
                                relativeLayout2.setBackgroundResource(resId);

我假设您尝试使用 R.drawable.1170 但没有成功,然后尝试了您发布的解决方案。

资源标识符必须以字符开头。那是因为 Java 标识符必须以字符开头。

在此处阅读更多内容Why can an identifier not start with a number?

很遗憾,您不能拥有具有数字名称的资源。也许你可以做一个解决方法:更改为 drawable_1170 如果你需要数字来比较或使用,你可以删除字符串 "drawable_".

String SnapShotFrame_TblTriviaLU = "1170";
RelativeLayout relativeLayout2 = (RelativeLayout) findViewById(R.id.gameplayLayout);
            int resId = getResources().getIdentifier("drawable_"+SnapShotFrame_TblTriviaLU, "drawable", getPackageName());
                                relativeLayout2.setBackgroundResource(resId);