1. 程式人生 > >批量解決Casting 'findViewById(R.id.X)' to 'X' is redundant

批量解決Casting 'findViewById(R.id.X)' to 'X' is redundant

在Android Studio 中build.gradle(Module:app) 如果compileSdkVersion >=26,進行findViewById操作會報 Casting 'findViewById(R.id.X)' to 'X' is redundant This inspection reports unnecessary cast expressions.
這裡寫圖片描述

大意為findViewById前的強制型別轉換是多餘的。

        mRvMsg = (RecyclerView)findViewById(R.id.rv_msg);
        mEtPort = (EditText) findViewById(R.id.et_port);

產生上邊的原因為,在compileSdkVersion >=26後,findViewById內部原始碼:

    @Nullable
    public <T extends View> T findViewById(@IdRes int id) {
        return getWindow().findViewById(id);
    }

返回值為範型T,且T extends View,因此不用向下強制型別轉換。
而compileSdkVersion < 26,其內部原始碼:

  public View findViewById(int
id) { throw new RuntimeException("Stub!"); }

返回值型別為 View,是RecyclerView、EditText等控制元件的父類,所以必須進行向下的強制型別轉換。

如果是新專案,個別幾處手動去掉即可,對於更變編譯版本的舊專案,且使用了大量的findViewById(沒有使用ButterKnife),這時就需要進行批量刪除,操作如下:
將滑鼠點選到警告的位置,然後按Alt+Enter,彈出修改方法
這裡寫圖片描述
依次選擇Cleanup code-Cleanup code on ...進入Specify Inspection Scope


,選擇Whole project後確認即可去除專案中全部強制型別轉換。
這裡寫圖片描述