androidcastingfindviewbyid

No need to cast the result of findViewById?


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?


Solution

  • 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 :)