【问题标题】:How to inject custom css in wbeview如何在 webview 中注入自定义 css
【发布时间】:2017-03-04 06:54:36
【问题描述】:

我正在尝试将自定义 css 添加到 android 应用程序中的 webview 内容,但它在 webview 中没有显示任何效果,可能是它尚未成功添加。

我的自定义字体 css:

/* normal */
@font-face {
   font-family: 'PT_Sans-Web';
   font-style: normal;
   font-weight: 400;
   src: local('PT_Sans Web Regular'), local('PT_Sans-Web-Regular'),url(file:///android_asset/fonts/PT_Sans-Web-Regular.ttf);
}

/* bold */
@font-face {
   font-family: 'PT_Sans-Web';
   font-style: normal;
   font-weight: 700;
   src: local('PT_Sans Web Bold'), local('PT_Sans-Web-Bold'), url(file:///android_asset/fonts/PT_Sans-Web-Bold.ttf);
 }

style.css

body {
font-family: PT_Sans-Web;
color: #4DB2EC;
font-size: 15pt;
width: 100%;
background: #fff;
}

strong {
font-weight: bold;
}

embed,object,img{display: block; max-width:100%; height: auto;}
.frame {width: 100%} 
#templates{display:none}
.subs-loading {width: 90%; margin: 2em auto; font-size: 1.5em; }
#subscriptions {
position: relative;
}

#container {
padding: 16px;
}

p {
font-family: PT_Sans-Web;
color: #4DB2EC;
font-size: 7pt;
width: 100%;
background: #fff;
line-height:11.38pt
}

h1 {
font-size: 2em;
line-height: 1.2em;
font-weight: bold;
color: #222;
margin: .1em 0 .2em;
}

在 webview 中加载代码:

mWebView.loadDataWithBaseURL(
            "file:///android_asset/",
            content,
            "text/html",
            "utf-8",
            null);
string content = "<!DOCTYPE html><html><head><meta charset='UTF-8' />"
            + "<meta name='viewport' content='width=device-width, initial-scale=1'>"
            + "<link rel='stylesheet' type='text/css' href='pt_sans.css'>"
            + "<link rel='stylesheet' type='text/css' href='webview.css'>"
            + "<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">"
            + "</head><body>"
            + mPostContent
            + "</body></html>";

我正在使用带有 webChromeclient 的 webview。但这在 webview 中没有显示任何效果。难道我做错了。在 webview 中添加 css 的更好方法。

在打开 webview 时,我在日志中收到此错误:

E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)

在测试设备 nexus 5x 并在其他设备上正常工作时出现此错误。

【问题讨论】:

    标签: android html css webview android-webview


    【解决方案1】:

    css 文件放入assets 文件夹,然后在html 中寻址。像这样更新您的 content 变量:

    string content = "<!DOCTYPE html><html><head><meta charset='UTF-8' />"
            + "<link rel=\"stylesheet\" href=\"file:///android_asset/style.css\">" //<-- Add this line
            + //...
    

    【讨论】:

    • 它在带有 android 6 的 one plus 测试设备中工作,但在带有 android 版本 7 的 nexus 5x 中出现此错误“E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)”
    • 我不知道这个错误,但它显然与 OpenGL 有关并且不在你的控制范围内。我认为你应该忽略它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-06
    • 2011-06-24
    相关资源
    最近更新 更多