Error on findViewById after upgrading to compile s

2019-06-16 19:58发布

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

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

4条回答
别忘想泡老子
2楼-- · 2019-06-16 20:37

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
查看更多
闹够了就滚
3楼-- · 2019-06-16 20:43

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.

查看更多
Melony?
4楼-- · 2019-06-16 20:56

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)
查看更多
孤傲高冷的网名
5楼-- · 2019-06-16 20:59

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);
}
查看更多
登录 后发表回答