动态设置ImageView的来源android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3516530/
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
set source of ImageView dynamically android
提问by Kyle
I have an ImageView on my scene that I would like to set the source of dynamically based on user input.
我的场景中有一个 ImageView,我想根据用户输入动态设置源。
Let's say I have 4 images in my drawable folder: aaa.png, bbb.png, ccc.png, and ddd.png.
假设我的 drawable 文件夹中有 4 个图像:aaa.png、bbb.png、ccc.png 和 ddd.png。
When my application loads I set the image to: aaa.png
当我的应用程序加载时,我将图像设置为:aaa.png
myImageView.setImageResource(R.drawable.aaa);
now I have an EditText where a user can type in bbb and I want to change the image source to be the bbb.png, or user enters ccc, change source to ccc.png etc.
现在我有一个 EditText,用户可以在其中输入 bbb,我想将图像源更改为 bbb.png,或者用户输入 ccc,将源更改为 ccc.png 等。
how can I dynamically set the parameter in setImageResource()? I tried playing around with the Drawable object to no avail...
如何在 setImageResource() 中动态设置参数?我尝试玩弄 Drawable 对象无济于事......
采纳答案by Yoni Samlan
If you want to allow open text input, you'll either have to use raw assetsto fetch them by string name (see the sidenote on that page), or else use magical Java reflectionto retrieve a field of the R class by name. Alternatively, you could keep a HashMap of strings to R.drawable integer values and look it up, but then you'd have to maintain that hashmap.
如果要允许打开文本输入,则必须使用原始资产按字符串名称获取它们(请参阅该页面上的旁注),或者使用神奇的Java 反射按名称检索 R 类的字段。或者,您可以将字符串的 HashMap 保留为 R.drawable 整数值并查找它,但是您必须维护该哈希图。
回答by Olsi Saqe
If you want to use reflections have a look at the code below:
如果您想使用反射,请查看以下代码:
R.drawable ourRID = new R.drawable();
Field photoNameField = ourRID.getClass().getField("aaa");
myImageView.setImageResource(photoNameField.getInt(ourRID));
Hope it helps.
希望能帮助到你。
回答by CaseyB
If you only want it to display images that you have loaded in your drawables you can use a Spinner
where the id for the item is set to be the resource for the Drawable
. That would be easier on your part and easier for the user.
如果您只希望它显示您已加载到可绘制对象中的图像,您可以使用 a Spinner
,其中项目的 id 设置为Drawable
. 这对您来说会更容易,对用户来说也会更容易。