java android以编程方式从字符串更改背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10207912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:02:33  来源:igfitidea点击:

android change background image programmatically from string

javaandroid

提问by Arthur Kushman

Possible Duplicate:
Setting Android images from string value

可能的重复:
从字符串值设置 Android 图像

I need to change background image programmatically on Android with source string I have. For example I have an array of strings gotten from XML file "source1", "source2" etc., so how can I set them to background as images? I saw examples like mTextView.setBackgroundResource(R.drawable.myResouce);, but I don't understand how to set mySource from a String. May be it is possible through drawable object?

我需要使用我拥有的源字符串在 Android 上以编程方式更改背景图像。例如,我有一个从 XML 文件“source1”、“source2”等获取的字符串数组,那么如何将它们设置为背景图像?我看到了类似的例子 mTextView.setBackgroundResource(R.drawable.myResouce);,但我不明白如何从字符串设置 mySource。可能通过可绘制对象有可能吗?

回答by Venky

Keep your images name inside drawables same as of in String.xml.

将您的图像名称保留在与 String.xml 中相同的可绘制对象中。

Say for eg: images.pngit should be imagesin String.xml

例如说:images.png它应该是String.xml 中的图像

If you pass this name to getResourceId()it will returns you Drawable with that String Variable.

如果您将此名称传递给getResourceId(),它将返回带有该字符串变量的 Drawable。

public static int getResourceId(Context context, String name, String resourceType) {
    return context.getResources().getIdentifier(name, resourceType, context.getPackageName());
}

int iconId = getResourceId(Activity.this, image, "drawable");    

ImageView categoryIcon = (ImageView) v.findViewById(R.id.category_icon);
categoryIcon.setImageResource(iconId);