升级到编译sdk版本后findViewById出错

问题描述 投票:8回答:4

升级到编译SDK版本26后,所有findViewById显示错误:

没有足够的信息来推断有趣的findViewById(id:Int)中的参数T:T!

android kotlin android-8.0-oreo
4个回答
15
投票

这是因为从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);
}

4
投票

例如,在纯Java中,您将拥有它

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

在Kotlin你可以用它

val textView = findViewById<TextView>(R.id.textview1)

0
投票

因为你把javakotlin混淆,用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中。


0
投票

这是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
© www.soinside.com 2019 - 2024. All rights reserved.