我通常做的是,创建一个自定义 TextView 并将其设置为我的内容的视图,
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTextView(Context context) {
super(context);
}
public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Regular.ttf"));
} else {
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Light.ttf"));
}
}
}
现在只需像这样用自定义的 TextView 替换常规的 TextView,
<TextView
android:id="@+id/R.id.srno"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
进入,
<com.example.CustomTextView
android:id="@+id/R.id.srno"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
这将用自定义的 TextView 更改普通的 TextView,从而添加字体。
注意:确保您已经创建了一个名为“fonts”的文件夹并将字体文件放在那里。
如果也可以通过添加一行来自定义和添加不同的字体,
例如如果你使用,
android:textStyle="bold"
它将设置字体类型 Roboto-Regular.ttf。这是在 CustomTextView 类中定义的,
if (style == Typeface.BOLD) {
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Regular.ttf"));
}