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?
Thus your cast is redundant. Before API level 26, the method findViewById returned the reference of View class. So you needed to cast it. But starting from API level 26, it has been updated and it returns subclass of View using template so that you can assign the returned reference without casting.
Before API level 26, the method findViewById returned the reference of View class. So you needed to cast it. But starting from API level 26, it has been updated and it returns subclass of View using template so that you can assign the returned reference without casting.
But starting from API level 26, it has been updated and it returns subclass of View using template so that you can assign the returned reference without casting. The example which you referred used the older API level while building the project, so you can see the casting there.
The reason why you get this is because findViewById returns View and this class already defines the method setOnClickListener. This means that even without doing the cast you can set the listener.
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 :)
According to this article:
The following function relies on Java’s generics automatic type inference in order to eliminate a need for manual casting:
protected <T extends View> T findViewById(@IdRes int id) {
return (T) getRootView().findViewById(id);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With