Home > Software engineering >  Kotlin: Styling Text in Snackbar with SDK later than 28
Kotlin: Styling Text in Snackbar with SDK later than 28

Time:07-25

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 Snackbar body:

val snackbarTextView = snackbar.view.findViewById(android.support.design.R.id.snackbar_text) as TextView

The problem setting the TextView with this code, is that it only works if your project targets SDK 28 or older, and legacy libraries are enabled. I am targeting SDK 30 and then the element 'design' in that line is always an unresolved reference.

My Snackbar code is as follows:

private fun showSnackbar(message: String)
{
    val coordinatorLayout: CoordinatorLayout = findViewById(R.id.coordinatorLayout)
    val snackbar = Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_INDEFINITE)
    snackbar.setBackgroundTint(Color.CYAN)
    snackbar.setAction("DISMISS", View.OnClickListener {
        // executed when DISMISS is clicked
    })
    snackbar.setTextColor(Color.BLACK)
    snackbar.show()
}

I can set the text color and size, but not other attributes like the font. How can I do this in Kotlin with the later SDKs? Thanks!

CodePudding user response:

from here

suppose you have your custom font inside res>font>myfont.ttf

create this class:

class CustomTypefaceSpan(var typeface: Typeface) : MetricAffectingSpan() {

    override fun updateDrawState(ds: TextPaint) {
        applyCustomTypeFace(ds, typeface)
    }

    override fun updateMeasureState(paint: TextPaint) {
        applyCustomTypeFace(paint, typeface)
    }

    private fun applyCustomTypeFace(paint: Paint, tf: Typeface) {
        paint.typeface = tf
    }
}

then :

private fun showSnackbar(message: String) {
    val ss = SpannableStringBuilder(message)
    val font = ResourcesCompat.getFont(this, R.font.myfont)
    ss.setSpan(CustomTypefaceSpan(font!!), 0, message.length, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)

    val coordinatorLayout: CoordinatorLayout = findViewById(R.id.coordinatorLayout)
    val snackbar = Snackbar.make(coordinatorLayout, ss, Snackbar.LENGTH_INDEFINITE)
    snackbar.setBackgroundTint(Color.CYAN)
    snackbar.setAction("DISMISS", View.OnClickListener {
        // executed when DISMISS is clicked
    })
    snackbar.setTextColor(Color.BLACK)
    snackbar.show()
}
  • Related