Does ImageView.setImageURI(Uri uri) work with remote files?

前端 未结 2 1467
遇见更好的自我
遇见更好的自我 2021-01-17 16:00

Is it possible to load an image from a remote server using ImageView.setImageURI(Uri uri)?

2条回答
  •  攒了一身酷
    2021-01-17 16:27

    To load an image from a directory, it should be converted to a Drawable first. Here is a piece of code which can help:

    File file = new File ("/sdcard/1.jpg");
    
    ImageView imageView = (ImageView) findViewById(R.id.icon);
    
    imageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath()));
    

    Be warned that there is another method for ImageView called setImageURI(URI uri). This method is used to load external files; it doesn't work with the type File. For example, this code won't work:

    File file = new File ("/sdcard/1.jpg");
    
    ImageView imageView = (ImageView) findViewById(R.id.icon);
    
    imageView.setImageURI(Uri.fromFile(file));
    

    Thanks to Martin Wibbels for this post.

提交回复
热议问题