如何将String转换为Drawable [英] How can I convert String to Drawable
本文介绍了如何将String转换为Drawable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在drawable文件夹中有很多图标,它们的名称为String.如何访问可绘制文件夹并更改背景imageView(或任何视图),请动态使用这些名称.谢谢
I have many icon in drawable folder and I have their name as String. How can I access to drawable folder and change background imageView (or any view) use these name in dynamically. Thanks
推荐答案
可以使用反射来完成:
String name = "your_drawable";
final Field field = R.drawable.getField(name);
int id = field.getInt(null);
Drawable drawable = getResources().getDrawable(id);
或使用Resources.getIdentifier()
:
String name = "your_drawable";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);
然后在两种情况下都使用它来设置可绘制对象:
Then use this for setting the drawable in either case:
view.setBackground(drawable)
这篇关于如何将String转换为Drawable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文