Casting 'findViewById(R.id.)' to 'Button' is redundant

发布时间: 2018-12-12 23:18:40 作者: 大象笔记

参照着 Android 权威编程指南第三版中的代码示例

mTrueButton = (Button) findViewById(R.id.true_button);

Android Studio 提示错误:

Casting 'findViewById(R.id.)' to 'Button' is redundant

redundant: 多余的意思。

查了一下,从 API 26 开始,findViewById 会判断对应 layout xml 中的定义类型,做自动类型转换。

<Button
    android:id="@+id/true_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/true_button" />

而 gradle 中指定的 API 为 28。

所以,去掉 Button 即可,代码更改为

mTrueButton = findViewById(R.id.true_button);
我是一名山东烟台的开发者,联系作者