我想将自定义字体嵌入到我的 Android 应用程序中。我不使用 TextView 所以这样的教程this one https://stackoverflow.com/questions/3424165/can-i-embed-a-custom-font-in-an-android-application(如何在 TextView 中使用自定义字体)没有帮助。
就我而言,内容取自 SQLite 数据库并使用 WebView 显示在屏幕上。我也不使用捆绑的 HTML 文件,所以本教程 https://stackoverflow.com/questions/1344080/how-to-use-custom-font-with-webview(如何在 WebView 中使用自定义字体)也没有解决我的问题。
仅供参考,这是我的代码:
public void initWebview()
{
WebSettings settings = wvContent.getSettings();
settings.setDefaultTextEncodingName("utf-8");
setContentView(R.layout.content);
wvContent = (WebView) findViewById(R.id.wvContent);
wvContent.setBackgroundColor(Color.argb(250, 250, 250, 250));
wvContent.getSettings().setSupportZoom(true);
wvContent.getSettings().setBuiltInZoomControls(true);
wvContent.setInitialScale(100);
wvContent.setWebViewClient(new WebViewClient()
{
public void onPageFinished(WebView view, String url)
{
if (pd != null)
{
pd.dismiss();
pd = null;
}
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
Log.i(CONTENT_TAG,"WebView link clicked; url = " + url);
try
{
String arrUrlPart[] = url.split("://");
if (arrUrlPart[0].equals("entry"))
{
String content = getContentByWord(arrUrlPart[1]);
showContent(content);
}
else if (arrUrlPart[0].equals("http"))
{
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
} catch (Exception ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return true;
}
});
}
字体存储在资源/字体似乎嵌入到应用程序中,我的问题是:
-
我如何以编程方式“强制”我的应用程序使用此字体?
- 我的问题有解决办法吗?
非常感谢。
从评论中this https://stackoverflow.com/a/7395170/16725回复,一个可能的解决方案似乎是使用loadDataWithBaseURL
同时提供资产文件夹作为基本 url,即
LoadData() 不起作用,但是
webView.loadDataWithBaseURL("file:///android_asset/",... 工作正常。
然后字体文件引用“/fonts/MyFont.otf”也应该可以工作。 –
雅克 2011-12-01 16:59
我假设捆绑你的font不是问题吧?
[Edit]为了澄清我的答案,我编写了一个小例子。在下面的代码中,我把Quicksand_Dash.otf
in 资源/字体, and twitter_logo.png
直接进入assets。 HTML 只是一个字符串常量,但您可以从 SQLite 数据库中检索它。本质其实只是为了使用loadDataWithBaseURL()
....
package oh.jolly.webview;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class WebviewTestActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.webview);
webView.loadDataWithBaseURL("file:///android_asset/", PAGE_HTML, "text/html", "UTF-8", "null" );
}
private final static String PAGE_HTML =
"<html>\n" +
" <style type=\"text/css\"> \n" +
" @font-face { \n" +
" font-family: MyFont; \n" +
" src: url(\"file:///android_asset/fonts/Quicksand_Dash.otf\") \n" +
" } \n" +
" body { \n" +
" font-family: MyFont; \n" +
" font-size: medium; \n" +
" text-align: justify; \n" +
" } \n" +
" </style> \n" +
" <body>\n" +
" I've got a sinking feeling...<br>\n" +
" <img src=\"file:///android_asset/twitter_logo.png\" />\n" +
" </body>\n" +
"</html>";
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)