Android Kotlin有条件地调用不同且不推荐使用的构造函数
我有一个用Kotlin编写的Android应用程序,它有一个扩展了DigitsKeyListener的类Android Kotlin有条件地调用不同且不推荐使用的构造函数,android,kotlin,constructor,deprecated,keylistener,Android,Kotlin,Constructor,Deprecated,Keylistener,我有一个用Kotlin编写的Android应用程序,它有一个扩展了DigitsKeyListener的类BaseKeyListener。我的最低SDK版本是21。该类当前正在调用不推荐使用的构造函数。然而,新的构造器仅在API级别26及以上可用。 如何根据API级别有条件地调用构造函数 我基本上是在前一段时间发布了Android的,但是这个解决方案在Kotlin中似乎不起作用 在科特林,我的班级现在看起来是这样的: // primary constructor 'DigitsKeyListene
BaseKeyListener
。我的最低SDK版本是21
。该类当前正在调用不推荐使用的构造函数。然而,新的构造器仅在API级别26及以上可用。
如何根据API级别有条件地调用构造函数
我基本上是在前一段时间发布了Android的,但是这个解决方案在Kotlin中似乎不起作用
在科特林,我的班级现在看起来是这样的:
// primary constructor 'DigitsKeyListener' shows lint warning about deprecation.
abstract class BaseKeyListener() : DigitsKeyListener() {
}
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)
}
如果我应用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()
如何解决这个问题?您链接的Java解决方案基本上只是忽略了不推荐使用的构造函数,而只使用不推荐使用的构造函数。我认为你最后的解决方案是最好的。它的使用并不比直接使用DigitKeyListener差——您仍然需要检查SDK版本 我在上面看到的一个小问题是,您的第一个构造函数隐式调用空的超级构造函数,从而通过本质上是一种语言攻击来避免弃用警告。真的,在我看来,这似乎是Kotlin的代码检查器中的一个bug。我认为显式调用超级构造函数并在您自己的类中弃用此构造函数更合适。所以我会让它看起来像这样:
// primary constructor 'DigitsKeyListener' shows lint warning about deprecation.
abstract class BaseKeyListener() : DigitsKeyListener() {
}
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)
}
这在功能上不会改变它的工作方式,但在不反对裸构造函数的情况下,很容易在任何地方意外地使用被反对的DigitKeyListener版本
在使用网站上,虽然很痛苦,但看起来就像你在上面一样,除了你会把
@Suppress(“DEPRECATION”)
放在那行前面,以确认不推荐警告。我不推荐你提到的构造函数。很好,你提到,如果我直接使用DigitKeyListener,这真的没有什么区别。我没有意识到这一点。