升级到编译sdk版本后,findViewById出现错误
升级到编译SDK
版本26后,所有findViewById
显示错误:
没有足够的信息来推断有趣的参数T findViewById(id:Int):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)
如果你想知道底下发生了什么事情,那么将底层方法改为
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
混淆了java
,使用android studio 3.0
你可以使用kotlin
代替java
语法,或者你可以使用Android官方博客
另请阅读Get Started with Kotlin on Android
更新:函数签名View findViewById(int id)
已经升级到<T extends View>T findViewById(int id)
表示它正在应用推理机制,用于返回类型,其中T extends View
表示View或它的子类型
注意:就像刚才提到的那样,Applying cast仍然不会产生任何错误,但是对于使用不必要的cast来说只是一个不起眼的警告 ,但是可能是kotlin类型推断中的一个错误,而不是java中的错误。