且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在WebView中使用本地图像渲染本地HTML文件

更新时间:2023-11-10 20:05:34

按照CommonWare的建议,我将回答这个问题并说明对我有用的方法.我还能够独立于文本缩放图像.

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.

当我的图像和html文件位于res/raw目录中时,我无法渲染该图像.我尝试了许多组合但都失败了.我不会说这是不可能的.

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.

DID的工作是在与src目录相同的级别上创建资产目录,然后将我的图像文件和html文件都放置在该目录中.正如CommonWare所指出的,文件的URL是

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"

即使目录名是"assets".

even though the directory name is 'assets'.

代码简化为

    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);

例如,"htmlpage"是

where 'htmlpage' is, for example,

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

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>

希望这可以为某人节省7个小时才能使它正常工作.

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