Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android O casting to findViewById not needed anymore? [duplicate]

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.

like image 259
Amro elaswar Avatar asked Jul 13 '17 23:07

Amro elaswar


People also ask

Why do we use findViewById in Android?

FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.

What does findViewById mean?

findViewById is the method that finds the View by the ID it is given. So findViewById(R. id. myName) finds the View with name 'myName'.

How does findViewById work on Android?

In the case of an Activity , findViewById starts the search from the content view (set with setContentView ) of the activity which is the view hierarchy inflated from the layout resource. So the View inflated from R. layout. toast is set as child of content view?

Which method is get view ID in Android Studio?

The Android SDK provided a method: findViewById() . Functionality-wise, this method performs a singular task — it will give you the reference to the view in XML layouts by searching its ID.


1 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.

like image 64
Marcin Orlowski Avatar answered Oct 05 '22 05:10

Marcin Orlowski