美文网首页
使用内部viewHolder时声明为static的原因

使用内部viewHolder时声明为static的原因

作者: 御风逍遥 | 来源:发表于2016-06-30 10:04 被阅读186次

    非静态内部类隐试持有外部类的强引用,此时内部类可以随意调用外部类中的方法和成员变量。使用static定义的内部类相对独立,不能访问外部类的非静态成员,占用资源更少。

    将viewHolder定义为static,可以将其与外部类解引用,如果不定义为static,当在viewHolder中执行复杂的逻辑或者做一些耗时的操作,就容易出现内存泄漏。如果是static则不能使用外部类资源,也就避免了相互引用造成的内存泄漏。当然,出现内存泄漏的情况是比较少见的。

    主要是防止内存泄漏,用static相当于直接写了一个.java文件,与外部类没有了依赖关系。

    但是在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!

    再说明一下内部类的使用:
    不常用的语法: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();
        }
    }

    相关文章

      网友评论

          本文标题:使用内部viewHolder时声明为static的原因

          本文链接:https://www.haomeiwen.com/subject/zbgxjttx.html