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.
FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.
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'.
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?
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.
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.
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