Android Kotlin有条件地调用了不同且不推荐使用的构造函数

问题描述 投票:2回答:1

[我有一个用Kotlin编写的Android应用程序,其中的类BaseKeyListener扩展了DigitsKeyListener。我的最低SDK版本是21。该类当前正在调用不建议使用的构造函数。但是,新的构造函数仅在API级别26及更高版本中可用。如何根据API级别有条件地调用构造函数?

我基本上是在不久前针对Android发布the same problem,但该解决方案似乎在Kotlin中不起作用。

在科特林,我的课现在看起来像这样:

// primary constructor 'DigitsKeyListener' shows lint warning about deprecation.
abstract class BaseKeyListener() : DigitsKeyListener() {

}

如果我将解决方案应用于Android问题,则会收到以下代码:

abstract class BaseKeyListener : DigitsKeyListener {

    // still results in deprecation warning
    constructor() : super()
}

还提供了另一种解决方案,如果我必须将构造函数设为私有并实现newInstance模式。但是我不能使用该解决方案,因为还有其他一些继承自BaseKeyListener的类,并且BaseKeyListener也很抽象。

我唯一能想到的是:

abstract class BaseKeyListener : DigitsKeyListener {

   constructor()

    @RequiresApi(Build.VERSION_CODES.O)
   constructor(locale: Locale) : super(locale)
}

但是结果是我必须为每个子类定义两个构造函数。如果使用该类,则每次使用的语言环境相同时,我都必须添加一个条件。

不幸的结果:

open class AmountKeyListener : BaseKeyListener {

    constructor() : super()

    @RequiresApi(Build.VERSION_CODES.O)
    constructor(locale: Locale) : super(locale)
}

// usage of the keyListener
editText.keyListener = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) KeyListenerUtil.AmountKeyListener(
        MY_LOCALE) else KeyListenerUtil.AmountKeyListener()

理想的解决方案应该是在一行上分配AmountKeyListener,而BaseKeyListener应该知道何时使用我们的自定义语言环境'MY_LOCALE'

editText.keyListener = KeyListenerUtil.AmountKeyListener()

如何解决此问题?

android kotlin constructor deprecated keylistener
1个回答
0
投票
我在上面看到的一个小问题是,您的第一个构造函数隐式调用了空的super构造函数,从而避免了实质上是语言hack的过时警告。确实,在我看来,这似乎是Kotlin代码检查器中的错误。我认为更合适的是显式调用超级构造函数,并在您自己的类中弃用该构造函数。所以我会让它看起来像这样:

abstract class BaseKeyListener : DigitsKeyListener { @Suppress("DEPRECATION") @Deprecated("Use the constructor with a locale if on SDK 26+.") constructor(): super() @RequiresApi(Build.VERSION_CODES.O) constructor(locale: Locale) : super(locale) }

这不会在功能上改变其工作方式,但是在不弃用裸露的构造函数的情况下,很容易在各处意外地使用DigitsKeyListener的弃用版本。

并且在使用站点上,虽然很痛苦,但看起来像上面的一样,除了您还要在该行的前面放置@Suppress("DEPRECATION")以确认弃用警告。
© www.soinside.com 2019 - 2024. All rights reserved.