Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 869
Eric Zhao Avatar asked Oct 10 '22 15:10

Eric Zhao


People also ask

Why do I need to cast findviewbyid?

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.

Can findviewbyid method return a subclass of a class?

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.

Is it possible to return a subclass of view 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.

Why does findviewbyid return a setonclicklistener?

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.


2 Answers

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

like image 149
Eduard B. Avatar answered Oct 14 '22 12:10

Eduard B.


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);
}
like image 25
zeroDivider Avatar answered Oct 14 '22 11:10

zeroDivider