将自定义字体设置为 TextView。
你有两种方式,先看第一种方式:
1.将您的字体文件添加到资产文件夹,如果不存在资产文件夹创建它。
2、创建CustomTypeface类,例如:
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Typeface;
public class CustomTypeface {
private static Typeface typefaseArialCondIt;
private static Typeface typefaseArialBold;
private static Typeface typefaseArialRegular;
public CustomTypeface() {
}
public CustomTypeface(Context context) {
AssetManager assets = context.getAssets();
CustomTypeface.typefaseArialCondIt = Typeface.createFromAsset(assets, "fonts/ArialCondIt.otf");
CustomTypeface.typefaseArialBold = Typeface.createFromAsset(assets, "fonts/ArialBold.otf");
CustomTypeface.typefaseArialRegular = Typeface.createFromAsset(assets, "fonts/ArialRegular.otf");
}
public static Typeface gettypefaseArialCondIt() {
return typefaseArialCondIt;
}
public static Typeface settypefaseArialCondIt(Typeface typefaseArialCondIt) {
return CustomTypeface.typefaseArialCondIt = typefaseArialCondIt;;
}
public static Typeface gettypefaseArialBold() {
return typefaseArialBold;
}
public static Typeface settypefaseArialBold(Typeface typefaseArialBold) {
return CustomTypeface.typefaseArialBold = typefaseArialBold;;
}
public static Typeface gettypefaseArialRegular() {
return typefaseArialRegular;
}
public static void settypefaseArialRegular(Typeface typefaseArialRegular) {
CustomTypeface.typefaseArialRegular = typefaseArialRegular;
}
}
3.并将自定义字体设置为TextView:
TextView yourTextView = (TextView) findViewById(R.id.textView1);
yourTextView.setTypeface(CustomTypeface.gettypefaseArialRegular);
或者第二种方法,使用您的字体创建自定义 TextView:
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class ArialTextView extends TextView {
public ArialTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ArialTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ArialTextView(Context context) {
super(context);
}
@Override
public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/ArialBold.otf"));
} else if (style == Typeface.NORMAL) {
setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/ArialRegular.otf"));
} else if (style == Typeface.ITALIC) {
setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/ArialCondIt.otf"));
}
}
}
并且在布局 xml 中您可以创建自定义 TextView,例如:
<com.your.package.ArialTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="TextView with your custom font"/>