findViewById為什么不用強(qiáng)轉(zhuǎn)了。

前言

工作時(shí)有個(gè)需求,把往Android28里面跑的代碼放到android 25上去跑,結(jié)果編譯就gg了/


image.png

在開發(fā)android 28 時(shí),用sonar檢測(cè)一個(gè)一個(gè)把強(qiáng)轉(zhuǎn)類型給刪的,現(xiàn)在又要我一個(gè)一個(gè)加回來,為什么?。?!

對(duì)啊 為什么呢。

原因

其實(shí)去高版本sdk上看,會(huì)發(fā)現(xiàn)

    @Nullable
    public final <T extends View> T findViewById(@IdRes int id) {
        if (id == NO_ID) {
            return null;
        }
        return findViewTraversal(id);
    }

   protected <T extends View> T findViewTraversal(@IdRes int id) {
        if (id == mID) {
            return (T) this;
        }
        return null;
    }

而在sdk 25的版本上代碼沒有這個(gè)泛型,這也就是為什么要強(qiáng)轉(zhuǎn)啦。 那是不是我把sdk25的find同步成高版本的實(shí)現(xiàn)我就不用在代碼上改了呢!哈哈哈~


    /**
     * Look for a child view with the given id.  If this view has the given
     * id, return this view.
     *
     * @param id The id to search for.
     * @return The view that has the given id in the hierarchy or null
     */
    @Nullable
    public final View findViewById(@IdRes int id) {
        if (id < 0) {
            return null;
        }
        return findViewTraversal(id);
    }
    /**
     * {@hide}
     * @param id the id of the view to be found
     * @return the view of the specified id, null if cannot be found
     */
    protected View findViewTraversal(@IdRes int id) {
        if (id == mID) {
            return this;
        }
        return null;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 用兩張圖告訴你,為什么你的 App 會(huì)卡頓? - Android - 掘金 Cover 有什么料? 從這篇文章中你...
    hw1212閱讀 13,958評(píng)論 2 59
  • 錄1.怎么實(shí)現(xiàn)通知欄到聊天界面的跳轉(zhuǎn) 32.聊天界面左右分隔怎么實(shí)現(xiàn),怎么實(shí)現(xiàn)優(yōu)化使其不出現(xiàn)錯(cuò)位 33.視頻,音頻...
    嚶嚶嚶999閱讀 2,419評(píng)論 3 35
  • 現(xiàn)在項(xiàng)目中用個(gè)第三方登錄,或分享已經(jīng)不是什么稀奇事了,但是要想把這個(gè)功能做好,那可就不容易了。估計(jì)到這里就有人會(huì)說...
    SmileUsers閱讀 5,464評(píng)論 4 62
  • 為了開始學(xué)一個(gè)東西前,我習(xí)慣性的會(huì)先問自己為什么?到底為什么我要開始學(xué)Flutter呢? 不確定你是為什么開始學(xué)習(xí)...
    Leesim閱讀 2,844評(píng)論 0 9
  • 久違的晴天,家長(zhǎng)會(huì)。 家長(zhǎng)大會(huì)開好到教室時(shí),離放學(xué)已經(jīng)沒多少時(shí)間了。班主任說已經(jīng)安排了三個(gè)家長(zhǎng)分享經(jīng)驗(yàn)。 放學(xué)鈴聲...
    飄雪兒5閱讀 7,812評(píng)論 16 22

友情鏈接更多精彩內(nèi)容