Rendering a local HTML file with a local image in WebView

雨燕双飞 提交于 2021-01-29 06:59:42

问题


I am trying to render a local html file with a local image in a WebView where the WebView is in a Dialog Box and not an Activity. The image is not being rendered, but the remainder of the info is displayed just fine.

There are countless solutions to this problem suggested in Stack Overflow, many with green check marks. None that I have tried have worked.

What I am doing is placing the html file and the image in res/raw The html file has a line referencing the image; I have tried different options all which have been stated somewhere in stack overflow as working, for example:

<img src="file:///android_res/raw/main_screen_crop.png" alt="Main Screen" width="525" height="290">

and

<img src="main_screen_crop.png" alt="Main Screen" width="525" height="290">

The text part of the html renders fine, but for the image I get just the 'alt' text inside an empty box with a thumbnail picture icon.

So the questions I have are:

  • Is accessing an image when the html of a WebView is rendered inside a Dialog Box different than an Activity making the suggested solutions invalid?
  • Some answers said "place the image in the assets directory and use the file:///..." to reference the image AND they indicated that this was required which contradicts other solutions. Is the use of the assets directory required?
  • Android has a 2018 tutorial https://www.youtube.com/watch?v=HGZYtDZhOEQ stating that many of the StackOverflow answers on how to handle WebView are just plain wrong but admit it is partly their fault due to out of date documentation ...

Here is my render code which works just fine for everything else!

    LayoutInflater inflater = ((Activity)context).getLayoutInflater();
    @SuppressLint("InflateParams") // Okay on dialog
    final View helpContent = inflater.inflate(R.layout.help_screen, null);

    // Get the Alert Dialog Builder
    android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);

    TextView customTitle = new TextView(context);
    // Customise Title here
    customTitle.setText(title);
    customTitle.setBackgroundColor(context.getResources().getColor(R.color.colorToolbarBackground));
    customTitle.setPadding(10, 10, 10, 10);
    customTitle.setGravity(Gravity.CENTER);
    customTitle.setTextColor(Color.WHITE);
    customTitle.setTextSize(20);

    builder.setCustomTitle(customTitle)
    WebView help = helpContent.findViewById(R.id.helpView);
    help.setWebViewClient(new WebViewClient()
    {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            view.loadUrl(url);
            return true;
        }
    });

    String helpText = readRawTextFile(htmlpage); // reads the html file
    help.getSettings().setAllowFileAccess(true);  // This did not help ...
    help.loadData(helpText, "text/html; charset=utf-8", "utf-8");
    builder.setView(helpContent); // put view in Dialog box

Any help, clarification, etc. as to what is correct will be greatly appreciated! Should add that the html file, when clicked on in Windows, renders fine in a browser.


回答1:


Following CommonWare's suggestion, I will answer this question and state what worked for me. I was also able to scale the image independently of the text.

I was unable to get the image to render when my image and html file were in the res/raw directory. I tried many combinations and failed. I will not state that it is impossible.

What DID work was creating an assets directory at the same level as the src directory and placing BOTH my image file and html file in that directory. As CommonWare pointed out, the URL for the files is

"file://android_asset/main_screen_crop.png"

even though the directory name is 'assets'.

The code simplifies to

    LayoutInflater inflater = ((Activity)context).getLayoutInflater();
    @SuppressLint("InflateParams") // Okay on dialog
    final View helpContent = inflater.inflate(R.layout.help_screen, null);

    // Get the Alert Dialog Builder
    android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);

    TextView customTitle = new TextView(context);
    // Customise Title here
    customTitle.setText(title);
    customTitle.setBackgroundColor(context.getResources().getColor(R.color.colorToolbarBackground));
    customTitle.setPadding(10, 10, 10, 10);
    customTitle.setGravity(Gravity.CENTER);
    customTitle.setTextColor(Color.WHITE);
    customTitle.setTextSize(20);

    builder.setCustomTitle(customTitle);

    WebView help = helpContent.findViewById(R.id.helpView);
    help.setWebViewClient(new WebViewClient()
    {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            view.loadUrl(url);
            return true;
        }
    });

    help.getSettings().setAllowFileAccess(true);
    help.loadUrl(htmlpage);

    builder.setView(helpContent);

where 'htmlpage' is, for example,

"file:///android_asset/layout_help.html"

The html file itself (with independent scaling of text and image) becomes:

<html>
<head>
<style>
    .gfg {
        width:auto;
        text-align:center;
        padding:2px;
    }
    img {
        max-width:100%;
                height:auto;
    }
</style>
</head>
<body>
<h3>Running the Application</h3>
After pressing start you will see a screen as follows:
<div class="gfg">
    <p id="my-image">
        <img src="file:///android_asset/main_screen_crop.png" alt="Main Screen"/>
    </p>
</div>
</html>

Hope this saves someone the 7 hrs it took me to get it to work.



来源:https://stackoverflow.com/questions/56186056/rendering-a-local-html-file-with-a-local-image-in-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!