akexorcist / Localization

[Android] In-app language changing library
Apache License 2.0
983 stars 154 forks source link

LocalizationActivity >= 1.2.6 does not work with ViewPump #116

Closed IamMitsuo closed 2 years ago

IamMitsuo commented 3 years ago

Issues

If a project uses ViewPump based libraries for pre/post-inflation, e.g. intercepting TextView inflation to change its typeface, it will not work and lead to app crash if the project includes LocalizationActivity version >= 1.2.6.

Example

MainApp.kt:

class MainApp : LocalizationApplication() {

    override fun onCreate() {
        super.onCreate()
        ViewPump.init(
            ViewPump.builder()
                .addInterceptor(SpanomaticInterceptor())
                .build()
        )
    }
}

ExampleActivity.kt:

class ExampleActivity : LocalizationActivity(R.layout.activity_example) {

    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        findViewById<TextView>(R.id.textview)?.text = getString(R.string.test)
    }

}

strings.xml

<string name="test">This is <annotation format="bold">a test string</annotation></string>

From the example code above, the TextView shows as "This is a test string" if using library version 1.2.5, but it will show as a normal text if using library version >= 1.2.6.

Causes

After some debugging, I found that since library version 1.2.6,

abstract class LocalizationActivity : AppCompatActivity, OnLocaleChangedListener {

...

override fun getBaseContext(): Context {
   return localizationDelegate.getApplicationContext(super.getBaseContext())
}

getBaseContext(): Context is added to fix an issue that base context is not updated in some version. Because of this method, the returned Context is does not contain attached ContextWrapper of type ViewPumpContextWrapper.

Workaround right now is to create a base Activity using LocalizationActivityDelegate and not override getBaseContext(): Context method, but I'm not sure what situation that causing baseContext is not updated in some version stated in release note