findViewById不需要强制类型转化啦
最近发现,在编写 findViewById 时,我没有进行类型转化,居然可以编译通过,我以为是 as 出问题了,然后 clean 几次,rebuild 几次都是一样,奇怪的是,项目照样可以运行,之后看源码才知道这是新的 api 新的支持。
在 Android Studio 的 build.gradle 中配置了 compile sdk 配置为 26 ,那么我们在编写 findViewById 时就不需要再像以前一样需要 cast 类型了。

具体的源码如下:
这段 code snippet 是从分别从 api26 和 api25 中摘抄下来的。现在从两段代码可以看出为什么不需要转化了吧。
-
下面两张图是 API26 的 activiy 和 view 中的源码。
api26源码
api26源码
-
下面两张图是 API25 的 activiy 和 view 中的源码。
api25源码
api25源码
我们以前是这么去 findViewById 的,但是在 as 中会提示这种 cast 是冗余的,建议去除。

通过下面3种方式去除as的提示:
-
第一种方式:直接手动删掉 cast 部分
-
第二,三种方式:就是如下图所示,鼠标移到强制转化的位置,按下 ctrl + 1(原谅我习惯了eclipse快捷键),as有弹出提示框
[图片上传失败...(image-5394a6-1513608577744)]-
选择第一选项,「Remove redundant cast(s)」 意思就是移除当前的强制转化,效果跟第一种方式一样。
-
选择第二项,「Cleanup code」,就将以上4个强制转化的去除,结果如下图所示:
-

这3方式都是只能在当前activity中去去除冗余的转化,但是对于比较大的项目来说,肯定存在很多 cast 操作,那么这时要怎么去处理呢?
下面举例的是两个 Activity 分别都有 findViewById 进行类型强制转化的代码,演示利用 as 工具将冗余的 cast 部分清除。


操作步骤:
分别点击 Analyze -> Code Cleanup -> While Project 即可

点击 OK 之后那么两个 Activity 强制转化部分就被清除掉了。当前也可以双击 shift 输入 Code Cleanup 更快进入这个这个页面。
网友评论