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

文章目录

    参照着 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);
    

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式