温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android中如何显示网络图片

发布时间:2022-04-16 16:16:35 来源:亿速云 阅读:564 作者:iii 栏目:开发技术

这篇文章主要介绍“Android中如何显示网络图片”,在日常操作中,相信很多人在Android中如何显示网络图片问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Android中如何显示网络图片”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

Android显示网络图片Step1:

1、创建你的Activity,本例中以ViewWebImageActivity说明;

2、ViewWebImageActivity中的代码如下:

  1. String imageUrl = "https://cache.yisu.com/upload/ask_collection/20210725/111/121401.jpg"; 

  2. //这就是你需要显示的网络图片---网上随便找的  

  3. Bitmap bmImg;   

  4. ImageView imView;  

  5. Button button1;   

  6. @Override   

  7. public void onCreate(Bundle savedInstanceState) {   

  8. super.onCreate(savedInstanceState);   

  9. setContentView(R.layout.main);   

  10. imView = (ImageView) findViewById(R.id.imview);   

  11. imView.setImageBitmap(returnBitMap(imageUrl));   

  12. }   

  13. public Bitmap returnBitMap(String url) {   

  14. URL myFileUrl = null;   

  15. Bitmap bitmap = null;   

  16. try {   

  17. myFileUrl = new URL(url);   

  18. } catch (MalformedURLException e) {   

  19. e.printStackTrace();   

  20. }   

  21. try {   

  22. HttpURLConnection conn = (HttpURLConnection) 
    myFileUrl.openConnection();   

  23. conn.setDoInput(true);   

  24. conn.connect();   

  25. InputStream is = conn.getInputStream();   

  26. bitmap = BitmapFactory.decodeStream(is);   

  27. is.close();   

  28. } catch (IOException e) {   

  29. e.printStackTrace();   

  30. }   

  31. return bitmap;   

  32. }

3、其中,returnBitMap(String url) 方法就是具体实现网络图片转换成bitmap。

Android显示网络图片Step2:

1、修改你的main.xml文件如下:

  1. < ?xml version="1.0" encoding="utf-8"?> 

  2. < LinearLayout xmlns:android=
    "http://schemas.android.com/apk/res/android" 

  3. android:orientation="vertical" 

  4. android:layout_width="fill_parent" 

  5. android:layout_height="fill_parent" 

  6. < ImageView   

  7. android:id="@+id/imview" 

  8. android:layout_width="wrap_content"   

  9. android:layout_height="wrap_content"   

  10. android:layout_gravity="center"   

  11. />   

  12. < /LinearLayout> 

Android显示网络图片Step3:

在你的AndroidManifest.xml文件的< /manifest>节点上面添加< uses-permission android:name="android.permission.INTERNET" />,这是由于Android有很多的权限限制,否则图片是不能在你的模拟器上显示的。

到此,关于“Android中如何显示网络图片”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI