【发布时间】:2014-11-27 10:23:35
【问题描述】:
我正在致力于在 android 应用程序中实现自定义字体..我想使用 style.XML 为整个应用程序使用一种自定义字体,或者可能是其他选项。
【问题讨论】:
标签: android
我正在致力于在 android 应用程序中实现自定义字体..我想使用 style.XML 为整个应用程序使用一种自定义字体,或者可能是其他选项。
【问题讨论】:
标签: android
在 Android 中没有简单的内置方法可以做到这一点。
您可能想查看Calligraphy,这是一个开源项目,可以轻松更改整个应用的字体。
【讨论】:
我遇到了同样的问题,但我没有找到使用 .xml 文件的方法, 最后我继承 TextView 和 EditText 并通过代码应用字体
将 .otf 文件放在项目中的资产/字体库中
创建一个继承自 TextView 的 TextViewFont 类
公共类 TextViewFont 扩展 TextView
{
私有 int mType = 0;
public TextViewFont(Context context)
{
this(context,null,0);
}
public TextViewFont(Context context, AttributeSet attrs)
{
this(context,attrs,0);
}
public TextViewFont(Context context, AttributeSet attrs, int defStyle)
{
super(context,attrs,defStyle);
init(context,attrs);
}
public void setType(int type){
this.mType= type;
Typeface tf;
switch (mType)
{
case 0:
tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/xxx-light.otf");
setTypeface(tf);
break;
case 1:
tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/xxx-regular.otf");
setTypeface(tf);
break;
case 2:
tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/xxx-bold.otf");
setTypeface(tf);
break;
}
}
private void init(Context context, AttributeSet attrs )
{
if (attrs != null)
{
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.TextViewFont,
0, 0);
try
{
TypedValue tv = new TypedValue();
if (a.getValue(0, tv))
{
mType = (int)tv.data;
}
mType = a.getInteger(R.styleable.TextViewFont_fontType,0);
}
finally
{
a.recycle();
}
}
if (!isInEditMode())
{
Typeface tf;
switch (mType)
{
case 0:
tf = Typeface.createFromAsset(context.getAssets(), "fonts/xxx-light.otf");
setTypeface(tf);
break;
case 1:
tf = Typeface.createFromAsset(context.getAssets(), "fonts/xxx-regular.otf");
setTypeface(tf);
break;
case 2:
tf = Typeface.createFromAsset(context.getAssets(), "fonts/xxx-bold.otf");
setTypeface(tf);
break;
}
}
}
}
3.xml布局文件中使用示例
在你使用自定义视图的文件的头部添加
xmlns:custom="http://schemas.android.com/apk/res-auto"
并将自定义类添加为任何其他视图元素
<xxxx.xxxx.xxxx.TextViewFont
android:id="@+id/xxxxx"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="abcdEFGH 123"
android:textAppearance="@style/xxxxxxx"
custom:fontType="Regular" />
<resources>
<declare-styleable name="TextViewFont">
<attr name="fontType" format="enum">
<enum name="Light" value="0"/>
<enum name="Regular" value="1"/>
<enum name="Bold" value="2"/>
</attr>
</declare-styleable>
</resources>
【讨论】: