android - PrintManager.print() 并更改了 attachBaseContext 中的语言环境

标签 android kotlin android-print-framework

我正在使用此扩展来更改我的应用程序的区域设置:

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)
}

主要 Activity :

override fun attachBaseContext(newBase: Context?) {
        super.attachBaseContext(newBase?.changeLanguage(prefs.language))
}

这适用于除打印以外的所有内容。 当我尝试打印时,我得到 java.lang.IllegalStateException: Can print only from an activity

另一个模块中的PrintFragment:

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)
}

有什么办法可以解决这个问题吗?

我现在切换回 context.resources.updateConfiguration(config, context.resources.displayMetrics)。希望他们不要过早删除它。

最佳答案

您可以将原始上下文从 fun attachBaseContext(newBase: Context?) 保存到某个 MainActivity 变量,然后在您的 PrintFragment 中使用它用于打印的变量。

与此处相同:Android N: PrintManager.print() results in java.lang.IllegalStateException: Can print only from an activity

关于android - PrintManager.print() 并更改了 attachBaseContext 中的语言环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54648474/

相关文章:

android - 在没有 BluetoothGATT 的情况下断开 BluetoothDevice

Android:如何区分清除通知栏中的所有事件和用户操作

android - 缺少 Kotlin View setEnabled 函数?

android - 有什么方法可以在 Kotlin 中扩展类时覆盖 setter 属性

KitKat 之前(api 18 之前)的 Android HTML 代码打印

android - 在 android 中创建、显示和打印 pdf 文档的最佳策略是什么

android - 通过 wi - fi 路由器将打印机连接到 android 设备

Android v4.0 CSS翻译

android - 如何一次组合多个解析查询

kotlin - 为什么 @Transient 不能与 val 字段一起使用?