Home » Android » java – Android O casting to findViewById not needed anymore?

java – Android O casting to findViewById not needed anymore?

Posted by: admin April 23, 2020 Leave a comment


I recently updated my android SDK and build tools to API 26 in Android Studio and I directly noticed that Android Studio was marking my view casts as “redundant” when I do something like this:

TextView itemName = (TextView) findViewById(R.id.menuItemName);

After some research, I found that since SDK 26, findViewById uses Java 8 features to return the same object type, but what I wanted to know is if it is completely safe to remove all casts. Will this cause any issues on Android prior to 26? Any more info on this would be helpful as I didn’t find much on the internet. Thanks in advance.

How to&Answers:

The method signature changed as you noticed and now it looks like:

public <T extends View> T findViewById(int id);

compared to the old (pre SDK 26) one:

public View findViewById(int id);

so as long as you use SDK 26 (or newer) to compile your project you can safely remove the casting from your code as you will be using new findViewById() which no longer requires it.

so having a lower minSdk than 26 will not cause an issue ?

No, neither minSdk nor targetSdk really matter. What matters is compileSdk which must be 26 or higher.