C. Moulinet
C. Moulinet

Reputation: 204

Kotlin easily access resources outside of an activity

I'm new at Android and Kotlin. I'm trying to create a ResourcesHelper class to easily access my custom colors and fonts from any other custom class in my app. But in this helper I don't have any context. I've read ways to get the context extending the Application class but then compiler says I can't access this context in my ResourcesHelper companion object as it would create memory leaks. Also I ended up with optional chained.

Here is how I would like to be able to use it :

class ResourcesHelper {

    companion object {
        val lightBlue = resources.getColor(R.color.lightBlue)
        val customBlue = resources.getColor(R.color.customBlue)
        // [...]    
        val fontAwesome = resources.getFont(R.font.fontawesome)
        val lemonMilk = resources.getFont(R.font.lemonmilk)
    }
}

enum class ButtonStyle {
    MENU,
    // [...]
    VICTORY
}

class CustomButton(c: Context, attrs: AttributeSet) : Button(c, attrs) {

    var isButtonActivated = false

    fun setStyle(style: ButtonStyle) {
        setBackgroundColor(ResourcesHelper.transparent)

        when(style) {
            ButtonStyle.MENU -> {
                setText(R.string.menu_button)
                typeface = ResourcesHelper.lemonMilk
                setBackgroundColor(ResourcesHelper.customRed)
                setTextColor(ResourcesHelper.white)
            }
            // [...]
            ButtonStyle.VICTORY -> {
                setText(R.string.victory_button)
                typeface = ResourcesHelper.lemonMilk
                setBackgroundColor(ResourcesHelper.customRed)
                setTextColor(ResourcesHelper.white)
            }
        }
    }
}

I also read this post Android access to resources outside of activity but it's in Java and I have no idea on how to do it in Kotlin.

I am completely lost on what and how to do this... Or if there is a better way to achieve reaching resources from anywhere.

Thanks for your help

Upvotes: 3

Views: 4411

Answers (2)

Sachin Kasaraddi
Sachin Kasaraddi

Reputation: 597

For Color, String, etc system resources you can use the Resources class, as shown below

import android.content.res.Resources

    class ResourcesHelper {
    
        companion object {
            val lightBlue = Resources.getSystem().getColor(R.color.lightBlue)
    
        }
    
    }

Upvotes: 4

amatkivskiy
amatkivskiy

Reputation: 1291

If you want to support different Android versions I'll recommend to use ContextCompat. It provides unified interface to access different resources and backward compatibility for older Android versions.

For AnroidX use androidx.core.content.ContextCompat, for SupportV4: android.support.v4.content.ContextCompat.

val lightBlue = ContextCompat.getColor(context, R.color.lightBlue)
val customBlue = ContextCompat.getColor(context, R.color.customBlue)

Upvotes: 2

Related Questions