原文:http://blog.isming.me/2015/07/07/android-custom-font/

最近的一个项目中有个需求:app与webview需要统一使用自定义字体。

一:修改App的默认字体

1.把myfont.ttf放在assets/fonts 目录下

2.配置Calligraphy

dependencies {      compile  'uk.co.chrisjenx:calligraphy:1.2.0' }   githut地址:https://github.com/chrisjenx/Calligraphy

2.在 BaseApplication extends Application 的onCreate 方法中

 CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()                        .setDefaultFontPath("fonts/myfont.ttf")                        .setFontAttrId(R.attr.fontPath)                        .build()
3.在BaseActivity 中重写attachBaseContext方法
 protected void attachBaseContext(Context newBase) {        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));    }
二:修改webview里网页的字体:

1.对于本地的网页,在asset目录放字体文件,并在css中添加以下内容,自定义一个字体face,并且在需要的地方使用这个字体face即可。

@font-face {  font-family: 'MyCustomFont';  src: url('file:///android_asset/fonts/myfont.ttf'); }body{  font-family:"MyCustomFont";}

2.对于在线的网页,则需要把字体文件放到服务器,使用同样的方式定义字体face,应用到每个地方。

为了减少网页或者说服务器端的工作,可以使用本地注入的方式注入font-face的css,并对整个网页进行样式替换。

给webview自定义webViewClient,重写onPageFinish,在其中添加如下内容:

public void onPageFinished(WebView view, String url) {injectCSS();view.loadUrl("javascript:!function(){" +        "s=document.createElement('style');s.innerHTML="        + "\"@font-face{font-family:myhyqh;src:url('****/fonts/myfont.ttf');}*{font-family:myhyqh !important;}\";"        + "document.getElementsByTagName('head')[0].appendChild(s);" +        "document.getElementsByTagName('body')[0].style.fontFamily = \"myhyqh\";}()");super.onPageFinished(view, url);}

****/fonts/myfont.ttf  //这里的* 号是为了让它走:shouldInterceptRequest
重写vwebview的shouldInterceptRequest方法:

public WebResourceResponse shouldInterceptRequest(WebView view,String url) {WebResourceResponse response = super.shouldInterceptRequest(view, url);Log.i("webview","load intercept request:" + url); if (url != null && url.contains("myfont.ttf")) {        String assertPath ="fonts/myfont.ttf";        try {            response = new WebResourceResponse("application/x-font-ttf","UTF8", getAssets().open(assertPath));        } catch (IOException e) {            e.printStackTrace();        }    }return response;}

这样网页被新字体重新渲染就达到目的了



更多相关文章

  1. android webview将网页内容导出为图片和PDF方法
  2. 在PC使用Chrome访问wap网页
  3. android webview网页控件
  4. Android重写菜单增加系统自带返回键
  5. ViewGroup和LayoutParams之间的关系
  6. View学习(android)
  7. OKhttp3 get/post使用及获取网页源代码
  8. Android(安卓)onCreate方法被调用两次的解决方法
  9. Android(安卓)自定义View (一)

随机推荐

  1. Android(安卓)9.0中sdcard 的权限和挂载
  2. Android(安卓)自定义view完全解析--带你
  3. Android(安卓)ViewDragHelper(1)
  4. Android(安卓)网络:Retrofit 与 Kotlin
  5. Eclipse 重装Android(安卓)ADT 问题~解决
  6. android 渗透测试必备工具
  7. Android(安卓)Studio 2.2 预览 - 新的UI
  8. android的消息处理机制(图+源码分析)——Lo
  9. android全格式多媒体播放器(一:ffmpeg移植)
  10. Android中自定义PopupWindow,动态弹窗。