No need to cast the result of findViewById? No need to cast the result of findViewById? android android

No need to cast the result of findViewById?


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);}


In older versions:

AutoCompleteTextView name = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);

From Android Studio 3.0 with SDK 26:

AutoCompleteTextView name = findViewById(R.id.autoCompleteTextView);