2017-06-09 56 views

回答

14

这是因为,由于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); 
} 
0

因为你是confu唱javakotlin,与Android工作室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或它的子类型

注意:正如前面提到的,应用投射依然不会产生任何错误,但只是一个皮棉警告使用不必要的投射,但可能是kotlin类型推断中的错误,但不是在java中。

+1

我要澄清,这个问题是针对Kotlin项目的。使用Android O,底层的findViewById方法发生了变化,因此我们不必再施放它。在java中,我们不再需要投射。 – bond

4

在纯Java中,你将有例如

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

在科特林你可以走这

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

这科特林某种预期的错误修复它

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