升级到编译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(R.id.edit_text) 

如果你想知道底下发生了什么事情,那么将底层方法改为

 public  T findViewById(@IdRes int id) { return this.getDelegate().findViewById(id); } 

在纯Java中,您将拥有例如

 TextView textView = findViewById(R.id.textview1); 

在Kotlin你可以去这个

 val textView = findViewById(R.id.textview1) 

因为你使用kotlin混淆了java ,使用android studio 3.0你可以使用kotlin代替java语法,或者你可以使用Android官方博客

另请阅读Get Started with Kotlin on Android

更新:函数签名View findViewById(int id)

已经升级到T findViewById(int id)表示它正在应用推理机制,用于返回types,其中T extends View表示View或它的子types

注意:就像刚才提到的那样,Applying cast仍然不会产生任何错误,但是对于使用不必要的cast来说只是一个不起眼的警告 ,但是可能是kotlintypes推断中的一个错误,而不是java中的错误。

这是Kotlin某种types的预期的错误修复它

 val result = findViewById (R.id.textView_result) as TextView val button_sum = findViewById