Android ImageView.setImageURI 在尝试分配 R.drawable.X Uri 时不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2313148/
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-08-20 05:21:16  来源:igfitidea点击:

ImageView.setImageURI does NOT work when trying to assign a R.drawable.X Uri

android

提问by Qlimax

is related to:

与以下有关:

Need suggestion about a mixed "Uri / int id" images ambient

需要关于混合“Uri / int id”图像环境的建议

now my problem is that:

现在我的问题是:

ImageView imgView=(ImageView)findViewById(R.id.imgView);
Uri imgUri=Uri.parse("android.resource://my.package.name/"+R.drawable.image);
imageView.setImageURI(imgUri);

does NOT work . why?

不起作用。为什么?

i know that

我知道

imgView.setImageDrawable(Drawable.createFromStream(
                    getContentResolver().openInputStream(imgUri),
                    null));

work.

工作。

but that does NOT solve my problem. because I want to set the image with an uri independenty if this come from a resource or come from the camera ACTION_PICK intent...

但这并不能解决我的问题。因为如果这来自资源或来自相机 ACTION_PICK 意图,我想设置具有 uri 独立性的图像...

any suggestions are welcome. Thank you. Regards

欢迎提出任何建议。谢谢你。问候

回答by Norfeldt

Try this

尝试这个

Uri imgUri=Uri.parse("android.resource://my.package.name/"+R.drawable.image);
imageView.setImageURI(null); 
imageView.setImageURI(imgUri);

This is a workaround for refreshing an ImageButton, which tries to cache the previous image Uri. Passing nulleffectively resets it.

这是刷新 ImageButton 的一种变通方法,它尝试缓存先前的图像 Uri。通过null有效地重置它。

Solution suggested from this book: Sams Teach Yourself Android Application Development in 24 Hours- Highly recommendable to read.

本书建议的解决方案:Sams Teach Yourself Android Application Development in 24 Hours- 强烈推荐阅读。

回答by Christine

imageView.postInvalidate()works. Or imageView.invalidate()if you're on the UI thread.

imageView.postInvalidate()作品。或者,imageView.invalidate()如果您在 UI 线程上。

回答by Dan Alboteanu

your should do something like this

你应该做这样的事情

Uri imgUri = Uri.parse("android.resource://my.package.name/drawable/image_sky");

or if you want like this

或者如果你想要这样

Uri imgUri = Uri.parse("android.resource://" + getPackageName() + "/drawable/" + "image_sky");

回答by user49439

First of all see, whether you are not override onRestart method and refreshing it.

首先看看你是不是重写了onRestart方法并刷新了它。

If you will refresh the activity the image will not set.

如果您将刷新活动,则不会设置图像。