findViewById类型转换异常Casting

升级Android studio为最新版3.0后,在项目初始化控件使用findViewById时,

出现下面代码中的情况 : tv = findViewById(R.id.textView);   此时as没有提示代码错误;

按照经常写代码的习惯,都会写为tv = (TextView)findViewById(R.id.textView); 

此时将此行代码改为: tv = (TextView)findViewById(R.id.textView); 


as提示  Casting  ' findViewById(R.id.textView) ' to TextView is redundant


问题出现原因:

build.gradle(Module:app) 文件中,compileSdkVersion 26 , 问题就出在这里;


查找资料后才知道, android 从 API 26 之后,使用findViewById 可以直接写为 tv = findViewById(R.id.textView) ;

将 build.gradle(Module:app) ---》 compileSdkVersion 从26改为25;(为什么要改为25,因为25之前不会出现此情况,改为小于等于25的数字都可以)

点击 Sync Now后 ,再去看原来书写的代码,就会变成大家熟悉的

 tv = (TextView)findViewById(R.id.textView)。此时此行代码下方有条红线,直接Alt + Enter会提示:Cast to 'android.widget.TextView', 导入TextView即可。



猜你喜欢

转载自blog.csdn.net/xyl826/article/details/78554062