res폴더 안에 font 폴더를 만들고 otf/ttf 파일을 옮긴다<TextView
....
android:fontFamily=”@font/font_name”
...
/>
보통은 XML 에서 사용하지만 Kotlin으로 제어하려면
프로젝트/app 경로에서 assets폴더를 추가하고 otf/ttf 파일을 옮긴다
Typeface 형태로 바꿔준다
val customFont = Typeface.createFromAsset(context.assets, "font_name.otf")
binding.textView.typeface = customFont // 적용
TextView의 typeface 말고 SpannableString으로 지정할 때도 있다
TypefaceSpan 형태로 바꾸기 위한 커스텀 클래스를 만든다
class CustomFontSpan(private val newType: Typeface) : TypefaceSpan("") {
override fun updateDrawState(ds: TextPaint) {
applyCustomTypeFace(ds, newType)
}
override fun updateMeasureState(paint: TextPaint) {
applyCustomTypeFace(paint, newType)
}
private fun applyCustomTypeFace(paint: Paint, tf: Typeface) {
val old = paint.typeface
val oldStyle = old?.style ?: 0
val fake = oldStyle and tf.style.inv()
if (fake and Typeface.BOLD != 0) {
paint.isFakeBoldText = true
}
if (fake and Typeface.ITALIC != 0) {
paint.textSkewX = -0.25f
}
paint.typeface = tf
}
}
커스텀 클래스를 이용해서 setSpan() 메서드에 넣어준다
SpannableString("text").run {
val customFont = ResourcesCompat.getFont(context, R.font.font_name)
this.setSpan(CustomFontSpan(customFont), START, END, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
this
}.also {
binding.textView.text = it // 적용
}
val tempTitle = menu?.findItem(R.id.clear_data)?.title ?: return super.onCreateOptionsMenu(menu)
SpannableString(tempTitle).apply {
this.setSpan(CustomFontSpan(context), 0, this.length, 0)
}.also {
menu?.findItem(R.id.xxx)?.title = it
}
[Java]
for (int i = 0; i < menu.size(); i++) {
String tempTitle = menu.getItem(i).getTitle().toString();
SpannableString spannableTitle = new SpannableString(tempTitle);
spannableTitle.setSpan(CustomFontSpan(customFont), 0, spannableTitle.length(), 0);
menu.getItem(i).setTitle(spannableTitle);
}