Home » Android » android – Error on findViewById after upgrading to compile sdk version

android – Error on findViewById after upgrading to compile sdk version

Posted by: admin June 15, 2020 Leave a comment

Questions:

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

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

How to&Answers:

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);
}

Answer:

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)

Answer:

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.

Answer:

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