Set Background Drawable Resource from String

痴心易碎 提交于 2019-12-23 04:04:40

问题


I have looked everywhere but cannot find an example of programmatically setting a background resource from a string value?

As an example:

Drawable a = getResources().getDrawable( R.drawable.a );
Drawable b = getResources().getDrawable( R.drawable.b );
Drawable c = getResources().getDrawable( R.drawable.c );
abc.setBackgroundResource("b");

Is this possible or would I have to do it as a big switch statement?


回答1:


you have getResources().getIdentifier for this purpose. It returns the id of the resources from its name.

E.g.:

 int resId = getResources().getIdentifier("b", "drawable", getPackageName());

Here you can find the documentation.



来源:https://stackoverflow.com/questions/22449692/set-background-drawable-resource-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!