Android App Display Image From URL(Android 应用显示来自 URL 的图像)
问题描述
我正在寻找一个非常基本的功能.我正在尝试设计一个应用程序,我想要它做的就是从 URL 加载图像.我发现了一些问题和网站,但它们似乎都较旧且过时,但我认为我遇到的问题是将代码链接到 ImageView 的活动 main.xml.
I'm looking for a very basic function. I'm trying to design an app and all I want it to do is load an image from a URL. I've found a few questions and websites, but they all seem to be older and dated, but what I think I'm having issues with is linking the code to activity main.xml for ImageView.
如果您有任何建议或链接,我将不胜感激,谢谢.
Any suggestions or links you have I would greatly appreciate, thank you.
推荐答案
这就是我如何在图像视图中显示来自 url 的图像
您必须从主线程以外的线程调用此代码
Here, this is how I display image from url in the image view
you have to call this code from thread other than main thread
ImageView img = (ImageView) findViewById(R.id.imageView1);
try {
URL url = new URL("Your URL");
//try this url = "http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toURI());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
InputStream input = b_entity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(input);
img.setImageBitmap(bitmap);
} catch (Exception ex) {
}
注意不要忘记用try catch包围代码(我已经在这段代码中这样做了)
Be careful don't forget to surround the code with try catch(I have already done that in this code)
或者您可以使用 webview 从 url 加载图像
or you can use webview to load image from url
WebView web = (WebView) findViewById(R.id.webView1);
web.loadUrl("Your Url");
如果您尝试从资产文件夹 url 加载图像,则会像这样开始文件:///android_asset/yourimage.jpg"
否则像这样的普通互联网网址"http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"
if you are trying to load image from the assets folder url will start like this
"file:///android_asset/yourimage.jpg"
else normal internet url like this
"http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"
希望这对你有用祝你好运
hope this works for you Good Luck
这篇关于Android 应用显示来自 URL 的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android 应用显示来自 URL 的图像
基础教程推荐
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01