【发布时间】:2013-12-17 09:27:54
【问题描述】:
我有一个应用程序,我想在整个应用程序中更改文本的字体。
是否可以以编程方式或清单中的xml更改应用程序的字体。
【问题讨论】:
-
我相信这已经被回答了 n 次。请浏览论坛。
标签: android textview android-fonts
我有一个应用程序,我想在整个应用程序中更改文本的字体。
是否可以以编程方式或清单中的xml更改应用程序的字体。
【问题讨论】:
标签: android textview android-fonts
试试这个
1.将您的 ttf 文件放在 assets 文件夹中,并将这些行添加到您的 java 文件中
Typeface font = Typeface.createFromAsset(activity.getAssets(),"fonts/androidnation.ttf");
tv.setTypeface(font);
2.通过xml设置
【讨论】:
将字体放在字体文件夹中,然后使用以下代码。
TextView tv = (TextView) findViewById(R.id.appname);
Typeface face = Typeface.createFromAsset(getAssets(),"fonts/epimodem.ttf");
tv.setTypeface(face);
这是以编程方式设置字体的方法。
【讨论】:
在asset中创建fonts文件夹并粘贴你想粘贴的字体。
创建一个类。将其命名为 Typesafe.java
public enum TypeSafe {
HELVETICANEUELTCOMBD,
HELVETICANEUELTCOMBDCN,
HELVETICANEUELTCOMCN,
}
之后,在您的 Activity 或者如果您有 Utility 类中创建一个方法。
public void setTypeface(TextView textView, TypeSafe type, AssetManager assetManager){
if (TypeSafe.HELVETICANEUELTCOMBD.equals(type)) {
final Typeface typeface = Typeface.createFromAsset(assetManager, "fonts/HelveticaNeueLTCom-Bd.ttf");
textView.setTypeface(typeface);
} else if (TypeSafe.HELVETICANEUELTCOMBDCN.equals(type)) {
final Typeface typeface1 = Typeface.createFromAsset(assetManager, "fonts/HelveticaNeueLTCom-BdCn.ttf");
textView.setTypeface(typeface1);
}
}
在您的activity 中调用这些方法。
setTypeface(yourtextView, TypeSafe.HELVETICANEUELTCOMLT, getAssets());
【讨论】:
最简单的方法是创建自己的 TextView:
public class MyTextView extends TextView {
public DMTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// you need your TypefaceFile "myTypeface.ttf" in the assets folder of your project
setTypeface(Typeface.createFromAsset(context.getAssets(),"myTypeface.ttf"));
}
// add the other constructors if you want
}
现在,您可以在 xml 中的任何位置使用它:
<com.your.package.MyTextView ... > 就像普通的文本视图一样
可以通过缓存字体来改进它,因此您不必在每次引用您的 TextView 时再次创建它。
【讨论】: