【发布时间】:2012-08-30 04:36:29
【问题描述】:
我需要为整个应用程序设置自定义字体(.ttf 格式),我该怎么做? 如果可能,来自 Manifest 或 XML 将是最佳选择
【问题讨论】:
-
仅仅因为它被标记为重复,无法提供更好的答案:使用书法库来实现这一点。它甚至改变了 toasts 的字体。
我需要为整个应用程序设置自定义字体(.ttf 格式),我该怎么做? 如果可能,来自 Manifest 或 XML 将是最佳选择
【问题讨论】:
2014 年 9 月编辑:
对于仍然看到这个旧的可怕答案的人来说,真正好的答案就在这里:
https://stackoverflow.com/a/16883281/1154026
旧:
您最好的选择是:
所以
TextView text = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "yourfont.ttf");
text.setTypeface(font);
您的 .ttf 位于“assets”文件夹的根目录中。
【讨论】:
textview1,textview2 和textView3,那么您应该只对它们使用 setTypface(yourfont)。希望对您有所帮助。
你可以这样做。 创建一个自定义文本视图并在任何地方使用它
public class MyTextView extends android.widget.TextView
{
public MyTextView(Context context)
{
this(context, null);
}
public MyTextView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public MyTextView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs);
if (this.isInEditMode()) return ;
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SomeStyle);
final String customFont = a.getString(R.styleable.SomeStyle_font);
//Build a custom typeface-cache here!
this.setTypeface(
Typeface.createFromAsset(context.getAssets(), customFont)
);
}
}
将此添加到 attrs.xml
<declare-styleable name="SomeStyle">
<attr name="font" format="string" />
</declare-styleable>
然后在您的主题中,执行以下操作: 这将确保所有文本视图都将使用 MyTextView 样式
<item name="android:textViewStyle">@style/MyTextView</item>
现在我们可以使用此样式中的自定义属性来定义您的自定义字体。
<style name="MyTextView" parent="@android:style/Widget.TextView">
<item name="font">MyPathToFontInAssets.ttf</item>
</style>
所以每当你在项目中使用 MyTextView 时,它都会有你的自定义字体。
重要提示:字体不会被缓存,因此如果您打算使用此代码,您还应该构建一个自定义字体缓存,以便您可以为所有文本视图重复使用自定义字体。这将显着加快应用程序的速度!
更新:正如 Amir 所说,这与 Custom fonts and XML layouts (Android) 几乎相同,但我也使用 android 样式自动在应用程序中的所有文本视图上使用它。
【讨论】:
<item name="android:textViewStyle">@style/MyTextView</item> ** type="string"清除了错误
创建一个 TextView 子类并在任何地方使用它
public class RobotoTextView extends TextView {
public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public RobotoTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RobotoTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Light.ttf");
setTypeface(tf);
}
}
}
用法
<com.test.RobotoTextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
在java代码中你可以把它转换成TextView
【讨论】:
TextView tv=(TextView)findViewById(R.id.custom);
Typeface face=Typeface.createFromAsset(getAssets(),
"fonts/Verdana.ttf");
tv.setTypeface(face);
将字体文件放在/res/的fonts文件夹中
如果对我的回答有帮助,请点赞...
【讨论】:
您可以按照here 的建议扩展 TextView 并在上面设置您的字体,然后在整个应用程序中使用它。
【讨论】: