从接触控件开始,Android开发者最熟悉的一行代码应该就是:
Button button = (Button) findViewById(R.id.button);
我第一次写这行代码的时候,刚学Java没几天,还不明白(Button)是什么意思,只是跟着书上敲出来,后来知道是用括号是强制类型转换。
但是有一天,突然看到自己的代码,(Button)打上了灰色波浪线,并提示:
Casting 'findViewById(R.id.button)' to 'Button' is redundant less... (Ctrl+F1)
This inspection reports unnecessary cast expressions.
也就是说这样的类型转换是没有必要的
既然类型转换没有必要,就说明通过findViewById()方法返回的View已经是我们需要的类型了
Ctrl+点击,进去可以看到:
@SuppressWarnings("TypeParameterUnusedInFormals")
@Override
public <T extends View> T findViewById(@IdRes int id) {
return getDelegate().findViewById(id);
}
返回对象已经是具体的,继承自View的对象例如Button,而不是直接返回View
但是刚开始学习的时候,很多教程都有这种加括号进行类型转换的写法,其实是API版本原因。
从API 26开始,findViewById()方法已经像上面一样,会自动返回需要的类型
而查API 25的源码,很容易看到:
@Override
public View findViewById(@IdRes int id) {
return getDelegate().findViewById(id);
}
另推荐查源码的网站:
Android OS
网友评论