android viewholder静态,使用内部viewHolder时声明为static的原因

非静态内部类隐试持有外部类的强引用,此时内部类可以随意调用外部类中的方法和成员变量。使用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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值