升级到编译SDK
版本26后,所有findViewById
显示错误:
没有足够的信息来推断有趣的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)
因为你把java
与kotlin
混淆,用android studio 3.0
你可以使用kotlin
而不是java
语法,或者你可以使用Android official blog上提到的两者
另请阅读Get Started with Kotlin on Android
更新:功能签名View findViewById(int id)
已经升级到<T extends View>T findViewById(int id)
意味着它正在应用返回类型的推理机制,其中T extends View
表示View或它的子类型
注意:正如最初提到的,应用强制转换仍然不会产生任何错误,只是一个lint警告使用不必要的强制转换,但可能是kotlin类型推断中的错误,但不是在java中。
这是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