可能是重复问题:
是否可以为整个应用程序设置字体?
我需要为整个应用程序设置自定义字体(.ttf格式),该如何做呢? 如果可能的话,最好从清单或XML中进行设置。
可能是重复问题:
是否可以为整个应用程序设置字体?
我需要为整个应用程序设置自定义字体(.ttf格式),该如何做呢? 如果可能的话,最好从清单或XML中进行设置。
编辑于2014年9月:
对于仍在查看这个糟糕旧答案的人,真正好的答案在这里:
https://dev59.com/0nE85IYBdhLWcg3wkkbK#16883281
旧版内容:
你最好尝试这个:
所以
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)即可。希望能帮到你。 - Recomerpublic 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)
);
}
}
<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>
<item name="android:textViewStyle">@style/MyTextView</item>
中出现了错误,提示需要一个“type”属性。现在我该怎么办? - DroidLearner<item name="font">myfolder/myfont.ttf</item>
。 - Jelle 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/ 文件夹中。
如果我的回答有帮助,请点赞...