本文介绍了不再需要 Android O 转换到 findViewById?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在 Android Studio 中将我的 android SDK 和构建工具更新为 API 26,我直接注意到当我执行以下操作时,Android Studio 将我的视图转换标记为冗余":

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

经过一番研究,我发现从 SDK 26 开始,findViewById 使用 Java 8 功能返回相同的对象类型,但我想知道删除所有强制转换是否完全安全.这会在 26 之前的 Android 上导致任何问题吗?任何有关这方面的更多信息都会有所帮助,因为我在互联网上找不到太多信息.提前致谢.

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.

推荐答案

方法签名如您所见发生了变化,现在看起来像:

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

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

与旧的(SDK 26 之前的)相比:

compared to the old (pre SDK 26) one:

public View findViewById(int id);

因此,只要您使用 SDK 26(或更新版本)来编译您的项目,您就可以安全地从代码中删除转换,因为您将使用新的 findViewById() 不再需要它.

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.

那么低于 26 的 minSdk 不会导致问题吗?

不,minSdktargetSdk 都不重要.重要的是 compileSdk 必须是 26 或更高.

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

这篇关于不再需要 Android O 转换到 findViewById?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 21:57