使用內(nèi)部viewHolder時聲明為static的原因

非靜態(tài)內(nèi)部類隱試持有外部類的強引用,此時內(nèi)部類可以隨意調(diào)用外部類中的方法和成員變量。使用static定義的內(nèi)部類相對獨立,不能訪問外部類的非靜態(tài)成員,占用資源更少。

將viewHolder定義為static,可以將其與外部類解引用,如果不定義為static,當在viewHolder中執(zhí)行復雜的邏輯或者做一些耗時的操作,就容易出現(xiàn)內(nèi)存泄漏。如果是static則不能使用外部類資源,也就避免了相互引用造成的內(nèi)存泄漏。當然,出現(xiàn)內(nèi)存泄漏的情況是比較少見的。

主要是防止內(nèi)存泄漏,用static相當于直接寫了一個.java文件,與外部類沒有了依賴關(guān)系。

但是在stackoverflow答案卻是另外一回事:

If you declare the viewholder as static you can reuse it in other adapters. Anyway, I do not recommend to do it, create a new separated class and use it from multiple places, it does make more sense. One class for one purpose.

In the case of view holders, this classes will be only used inside the adapter, their instances should not go to the fragment or activity or elsewhere just by definition. This means having it static or non-static, in the case of view holders, is the same.

另一個類似的答案

By using static it just means you can re-use MyVh in other adapters. If you know for certain that you'll only need MyVh in that one adapter, then you should make it non-static.

If you will need it in other adapters it may even be better to just create it as a separate class entirely, rather than a nested class.

There should be no effects on performance for static vs non-static!

再說明一下內(nèi)部類的使用:
不常用的語法:outer.new MyInner();

class MyOuter {
    class MyInner {
    }
}
void use() {
    MyOuter outer = new MyOuter();
    MyOuter.MyInner inner = outer.new MyInner();
}

public class MyOuter {
    static class MyInner {
    }
    void use() {
        //MyOuter outer = new MyOuter();
        MyOuter.MyInner inner = new MyOuter.MyInner();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評論 19 139
  • 對象的創(chuàng)建與銷毀 Item 1: 使用static工廠方法,而不是構(gòu)造函數(shù)創(chuàng)建對象:僅僅是創(chuàng)建對象的方法,并非Fa...
    孫小磊閱讀 2,184評論 0 3
  • 有人說,不奮斗,你要青春做什么?不要在該奮斗的年紀選擇安逸,說的真好。 其實,我們都知道,人是矛盾的共同體。一方面...
    像話讀書爻閱讀 445評論 0 4
  • 漫長的等待著前男友的結(jié)果,不知不覺我和尹先生在網(wǎng)上聊了有兩個多月時間。 前男友的媽媽叫我給前男友送點錢和一些需要用...
    今在否閱讀 366評論 0 0
  • 1223 asdasd
    ZuoAZuoA閱讀 184評論 0 0

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