【问题标题】:Image load in webview or not?是否在 webview 中加载图像?
【发布时间】:2013-11-26 01:57:32
【问题描述】:

我正在使用 webview 来显示图像。我使用了 webview.loadUrl("imagepath");这些代码显示图像但 webview 无法加载图像然后我想在 webview 中显示我的默认图像。

【问题讨论】:

    标签: android webview android-webview


    【解决方案1】:

    您必须在图像路径前添加file:///

    你尝试过类似的东西

    // Exemple from asset folder
    webview.loadUrl("file:///android_asset/mu_image.jpg");
     // From external storage
    String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
    String imagePath = "file://"+ base + "/YOUR_FILE.jpg";
    webview.loadUrl(base);
    

    编辑(理解问题后...)

    你必须检查你的网络文件是否存在

    public static boolean exists(String URLName){
    try {
      HttpURLConnection.setFollowRedirects(false);
      // note : you may also need
      //        HttpURLConnection.setInstanceFollowRedirects(false)
      HttpURLConnection con =
         (HttpURLConnection) new URL(URLName).openConnection();
      con.setRequestMethod("HEAD");
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
       e.printStackTrace();
       return false;
    }
      }
    

    然后有 2 个选择: - 文件存在,显示它 - 或者,显示您的默认图像

    来源:Check if file exists on remote server using its URL

    【讨论】:

    • 图片路径如upload/student/image1.png。我只想在 webview 中不显示错误消息(如网页不可用),而不是加载学生的默认图像(如空白图像)。
    • 你的路径必须是 imagePath = "file://"+ base + "/upload/student/image1.png";我不明白你想要什么。如果没有什么可显示的,是不是要显示一些东西?
    • 如果没有可显示的内容,则显示默认图像。图片不在服务器上图片所在的设备中。
    • 非常感谢 azerto00。
    【解决方案2】:

    在 web 视图中加载图像不是一个好习惯。

    解决方案是使用某种图像加载器,最适合您的情况是 VOLLEY。它提供了比任何其他图像加载器更好的缓存和图像加载功能。

    这里是link

    【讨论】:

    • 还有github.com/nostra13/Android-Universal-Image-Loader 是一个很好很简单的库
    • VOLLEY 更加高效和有用,因为它在 GOOGLE I/O 中被讨论过,并且第一次看起来很难实现,但是当你使用它一次时,这样做永远不会成为问题...
    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 2014-06-21
    相关资源
    最近更新 更多