Error on findViewById after upgrading to compile s

2019-06-16 20:21发布

问题:

After upgrading to compile SDK version 26, all findViewById showing error:

not enough information to infer parameter T in fun findViewById(id: Int): T!

回答1:

This is because as of Android O, we don't need to cast it. There are a few options. Replace:

val textInput = findViewById(R.id.edit_text) as TextInputLayout

With either:

val textInput:TextInputLayout = findViewById(R.id.edit_text)

Or:

val textInput = findViewById<TextInputLayout>(R.id.edit_text)

If you want to know what happened under the covers, as of O underlying method changed to

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


回答2:

In pure Java you will have for example

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

In Kotlin you can go with this

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


回答3:

Because you are confusing java with kotlin , with android studio 3.0 you can use kotlin instead of java syntax or you can use both as mentioned on Android official blog

Also read about Get Started with Kotlin on Android

Update : The function signature View findViewById(int id)

has been upgraded to <T extends View>T findViewById(int id) mean it's applying the inference mechanism for return type where T extends View mean the View or it's sub-types

Note : So as mentioned initially ,Applying cast still won't generate any error but just a lint warning for using unnecessary cast but could be a bug in kotlin type inference but not in java.



回答4:

It's Kotlin some type expected error fix it

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