No need to cast the result of findViewById?

Eric Zhao picture Eric Zhao · Jul 4, 2017 · Viewed 47k times · Source

Recently i found that AndroidStudio reminds me to remove some class cast. I remember that in the old time, we have to cast the result of findViewById, but now it's not necessary.

The result of findViewById is still View, so i want to know why we don't need to cast the class?

I can't find any documents mentioned that, can anyone find any document?

Answer

Eduard B. picture Eduard B. · Jul 4, 2017

Starting with API 26, findViewById uses inference for its return type, so you no longer have to cast.

Old definition:

View findViewById(int id)

New definition:

<T extends View> T findViewById(int id)

So if your compileSdk is at least 26, it means that you can make use of this :)