有多种方式可以设置Android应用中的字体族(font family)。以下是一些常用的方法,并包含相应的代码示例:
TextView textView = findViewById(R.id.textView);
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/custom_font.ttf");
textView.setTypeface(typeface);
上述代码假设存在一个名为"custom_font.ttf"的字体文件在assets/fonts目录中。
public class CustomTextView extends androidx.appcompat.widget.AppCompatTextView {
public CustomTextView(Context context) {
super(context);
init();
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/custom_font.ttf");
setTypeface(typeface);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制额外的自定义内容
}
}
然后,在XML布局文件中使用自定义的TextView类:
上述代码假设存在一个名为"custom_font.ttf"的字体文件在assets/fonts目录中。
通过以上方式,你可以根据需要在Android应用中设置字体族。