为什么在 ViewHolder 模式中 ViewHolder 类应该是静态的? [英] Why in ViewHolder pattern should the ViewHolder class be static?

查看:29
本文介绍了为什么在 ViewHolder 模式中 ViewHolder 类应该是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想更好地理解以下我经常用来优化ListView

I am just trying to have a better understanding of the following pattern I regularly use to optimize ListView

我的阅读只是让我注意到一个事实,即静态内部类被视为顶级类.与成员类(非静态)相比,这样的东西有什么好处?

My readings only pointed me to the fact that a static inner class is treated as top level class. What is the benefit of such a thing compared to a member class (non static)?

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Comment comment = getItem(position);
    ViewHolder holder;
    if (convertView == null){
        holder = new ViewHolder();
        convertView = LayoutInflater.from(context).inflate(R.layout.mylayout, null);
        holder.nickname = (TextView) ((ViewGroup) convertView).findViewById(R.id.nickname);
        convertView.setTag(holder);
    }else{
        holder = (ViewHolder) convertView.getTag();
    }

    holder.nickname.setText(comment.getMember_nickname());
    CharSequence
    return convertView;
}

public static class ViewHolder{
    TextView nickname;
}

推荐答案

使用静态内部类的一个好处是,可以从静态方法访问内部类,而无需外部类的实例.

One benefit of using static inner class, is that the inner class can be accessed from static methods, without having an instance of the outer class.

如果内部类是非静态的:

If the inner class non-static:

class MyOuter {
    private int x = 7;
    public void makeInner() {
        MyInner in = new MyInner();
        in.seeOuter();
    }
    class MyInner {
        public void seeOuter() {
            System.out.println("Outer x is " + x);
        }
    }
}

public static void main(String[] args) {
    MyOuter mo = new MyOuter();
    MyOuter.MyInner inner = mo.new MyInner();
    inner.seeOuter();
}

如果内部类是静态的:

class BigOuter {
    static class Nest {void go() { System.out.println("hi"); } }
}

class Broom {
    static class B2 {void goB2() { System.out.println("hi 2"); } }
    public static void main(String[] args) {
        BigOuter.Nest n = new BigOuter.Nest();
        n.go();
        B2 b2 = new B2();
        b2.goB2();
    }
}

这篇关于为什么在 ViewHolder 模式中 ViewHolder 类应该是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆