Im using this extension to change the locale of my app:
fun Context.changeLanguage(language: String): ContextWrapper {
var context = this
val config = context.resources.configuration
if (language.isNotBlank()) {
val locale = Locale(language)
Locale.setDefault(locale)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
config.setLocale(locale)
} else {
config.locale = locale
}
context = context.createConfigurationContext(config)
}
return ContextWrapper(context)
}
MainActivity:
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(newBase?.changeLanguage(prefs.language))
}
This works fine for everything but printing.
When I try to print I get java.lang.IllegalStateException: Can print only from an activity
PrintFragment in another module:
activity?.also { context ->
val printManager = context.getSystemService(Context.PRINT_SERVICE) as PrintManager
val jobName = getString(R.string.print_document)
printManager.print(jobName, PrintPdfAdapter(context, printList), null)
}
Any ideas how I can get around this problem?
I switched back to context.resources.updateConfiguration(config, context.resources.displayMetrics) for now. Hoping they don't remove it too soon.
You can save the original context from
fun attachBaseContext(newBase: Context?)to someMainActivityvariable and then in yourPrintFragmentuse this variable for printing.Same as here: Android N: PrintManager.print() results in java.lang.IllegalStateException: Can print only from an activity