안녕하세요!
오늘은 안드로이드에서 메시지를 띄워주는 방법 중 하나인 Snackbar에 커스텀 폰트를 적용하는 방법에 대해
간단하게 설명 해드리고자 합니다😊
일반적으로 Snackbar를 이용할 때, 아래와 같은 코드를 사용합니다.
Snackbar.make(view, message, duration).show()
하지만 앱을 개발하다보면 자체 커스텀 폰트를 적용하는 경우가 많은데, 위 코드를 이용해 스낵바를 사용하게되면 시스템 폰트를 따라가도록 되어있습니다. 그래서 스낵바에 커스텀 폰트를 적용할 방법이 없을까하는 생각에 구글을 찾아본 결과,,,
StackOverFlow에서 좋은 코드를 찾았습니다!
예전에 찾은 코드들은 Snackbar style 내 TextView를 찾아 해당 뷰의 typeface를 바꾸는 식의 코드가 많았었는데, 안드로이드 버전에 따라 호환성 문제가 발생하는 경우가 있었습니다.
이번에 찾은 코드는 MetricAffectingSpan() 을 이용해 SpannableStringBuilder의 'span'을 세팅하는 방법을 사용하고 있습니다.
(+ 아래 코드는 추가적으로 message 폰트 외에도 action 버튼에 사용될 폰트까지 적용할 수 있는 코드입니다.)
class CustomTypefaceSpan(private val typeface: Typeface) : MetricAffectingSpan() {
override fun updateDrawState(paint: TextPaint?) {
paint?.let { p -> applyCustomTypeface(p, typeface) }
}
override fun updateMeasureState(paint: TextPaint) {
applyCustomTypeface(paint, typeface)
}
private fun applyCustomTypeface(paint: Paint, typeface: Typeface) {
paint.typeface = typeface
}
}
fun Context.showSnackbar(
view: View,
duration: Int,
message: String,
actionMessage: String = "",
actionEvent: () -> Unit = {}
) {
val messageStringBuilder = SpannableStringBuilder(message)
val customFont = ResourcesCompat.getFont(this, R.font.pretendard_medium)
customFont?.let { font ->
messageStringBuilder.setSpan(
CustomTypefaceSpan(font),
0,
message.length,
Spanned.SPAN_EXCLUSIVE_INCLUSIVE
)
Snackbar.make(view, messageStringBuilder, duration).apply {
if (actionMessage.isNotEmpty()) {
val actionMessageStringBuilder = SpannableStringBuilder(actionMessage)
actionMessageStringBuilder.setSpan(
CustomTypefaceSpan(font),
0,
actionMessage.length,
Spanned.SPAN_EXCLUSIVE_INCLUSIVE
)
setAction(actionMesageStringBuilder) {
actionEvent()
}
setActionTextColor(ContextCompat.getColor(this@showSnackbar, R.color.yellow))
}
}.show()
}
}
참고
https://stackoverflow.com/questions/73099407/kotlin-styling-text-in-snackbar-with-sdk-later-than-28
Kotlin: Styling Text in Snackbar with SDK later than 28
I am working on a Kotlin project and I wish to style the text in a Snackbar, specifically the text font. I have been to many websites that address this problem, but they all use this line in the Sn...
stackoverflow.com
'Android' 카테고리의 다른 글
[안드로이드 / Kotlin] 둥근 모서리 Bitmap 이미지 만들기 (0) | 2022.11.18 |
---|---|
[안드로이드 / Kotlin] RecyclerView 최상단 최하단 스크롤감지 (0) | 2022.11.11 |
[안드로이드] ConstraintLayout 뷰 밀림 문제 (0) | 2022.10.30 |
[안드로이드 / Kotlin] ViewPager2 setCurrentItem duration (0) | 2022.10.28 |
[안드로이드 / Kotlin] Moshi (2) | 2022.09.30 |