非靜態(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();
}
}