getString Outside of a Context or Activity

后端 未结 12 2087
遥遥无期
遥遥无期 2020-11-28 01:12

I\'ve found the R.string pretty awesome for keeping hardcoded strings out of my code, and I\'d like to keep using it in a utility class that works with models i

12条回答
  •  渐次进展
    2020-11-28 01:35

    Somehow didn't like the hacky solutions of storing static values so came up with a bit longer but a clean version which can be tested as well.

    Found 2 possible ways to do it-

    1. Pass context.resources as a parameter to your class where you want the string resource. Fairly simple. If passing as param is not possible, use the setter.

    e.g.

    data class MyModel(val resources: Resources) {
        fun getNameString(): String {
            resources.getString(R.string.someString)
        }
    }
    
    1. Use the data-binding (requires fragment/activity though)

    Before you read: This version uses Data binding

    XML-

    
    
    
    
    
        
    
    
    
    
    

    Activity/Fragment-

    val binding = NameOfYourBinding.inflate(inflater)
    binding.someStringFetchedFromRes = resources.getString(R.string.someStringFetchedFromRes)
    

    Sometimes, you need to change the text based on a field in a model. So you would data-bind that model as well and since your activity/fragment knows about the model, you can very well fetch the value and then data-bind the string based on that.

提交回复
热议问题