升级到编译SDK
26版后,全部findViewById
报错:
没有足够的信息来推断 fun findViewById(id: Int): T 中的参数 T!
升级到编译SDK
26版后,全部findViewById
报错:
没有足够的信息来推断 fun findViewById(id: Int): T 中的参数 T!
这是因为从 Android O 开始,我们不需要强制转换它。有几个选项。代替:
val textInput = findViewById(R.id.edit_text) as TextInputLayout
无论是:
val textInput:TextInputLayout = findViewById(R.id.edit_text)
或者:
val textInput = findViewById<TextInputLayout>(R.id.edit_text)
如果您想知道幕后发生的事情,从 O 底层方法更改为
public <T extends View> T findViewById(@IdRes int id) {
return this.getDelegate().findViewById(id);
}
例如,在纯 Java 中,您将拥有
TextView textView = findViewById(R.id.textview1);
在 Kotlin 你可以用这个
val textView = findViewById<TextView>(R.id.textview1)
这是 Kotlin 某种类型的预期错误修复它
val result = findViewById <TextView>(R.id.textView_result) as TextView
val button_sum = findViewById<Button>(R.id.button_sum) as Button
val editText_i1 = findViewById<EditText>(R.id.editText_i1) as EditText
因为您对 android studio 感到困惑java
,所以您可以使用kotlin
android studio而不是语法,也可以同时使用两者,如Android 官方博客中所述3.0
kotlin
java
另请阅读Get Started with Kotlin on Android
更新:函数签名
View findViewById(int id)
已升级为<T extends View>T findViewById(int id)
意味着它正在应用返回类型的推理机制,其中T extends View
意味着 View 或其子类型
注意:所以正如最初提到的,应用强制转换仍然不会产生任何错误,而只是使用不必要的强制转换的 lint警告,但可能是 kotlin 类型推断中的错误,但在 java 中不会。