user5459652
user5459652

Reputation:

Why I cannot override getString() in Activity

getString(...) is declared final in Context class in Android. Why it has to be final?

I will be checking translations stored in HashMap downloaded from our server so overriding getString(...) in our app BaseActivity seems obvious to me.

Upvotes: 3

Views: 1055

Answers (2)

S.Javed
S.Javed

Reputation: 403

Maybe a lot late to the party, but if someone is still looking for a solution, you could use the context wrapper and provide your own implementation of the resources. For example

class CustomResources(
    res: Resources,
    private val dynamicStringMap: Map<String, String>) {
   override fun getString(id: Int): String { 
        val name = getResourceEntryName(id)  
        return dynamicStringMap[name] ?: super.getString(id)
 }

and provide it with ContextWrapper like

class CustomContextWrapper(
    private val base: Context,
    private val dynamicStringMap: Map<String, String>) : ContextWrapper(base) {
   override fun getResources() = CustomResources(base.resources, dynamicStringMap)
}

and finally attach it to your mainActivity (in case single activity app, or each activity individually) https://jitinsharma.com/posts/taming-android-resources-and-layoutinflater-for-string-manipulation/

Upvotes: 0

m0skit0
m0skit0

Reputation: 25874

getString() is final because it is just calling getResources().getString() and getResources() is overridable, which means you can just extend Resources class and override its getString() method.

Upvotes: 1

Related Questions