findViewById 的转换结果是多余的

Pro*_*cky 3 android casting textview

我是 Android 新手,我正在做一些关于使用各种视图的练习。一个这样的例子是:

    TextView messageView = (TextView) findViewById(R.id.message);
Run Code Online (Sandbox Code Playgroud)

我的问题是:投射 TextView 有什么好处?我的 IDE 告诉我强制转换方法是多余的。是否有任何用例我想以这种方式进行投射?

Nab*_*ari 5

在 API 级别 26 之前,该方法findViewById返回View类的引用。所以你需要投射它。

//old signature
public View findViewById(int id){
    //
}
Run Code Online (Sandbox Code Playgroud)

但是从 API 级别 26 开始,它已更新并返回Viewusing 模板的子类,以便您无需强制转换即可分配返回的引用。

//new signature
public <T extends View > T findViewById(int id){
    //
}
Run Code Online (Sandbox Code Playgroud)

您引用的示例在构建项目时使用了较旧的 API 级别,因此您可以在那里看到转换。以前是强制性的,但现在没有必要了。所以你收到了警告。