欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ListView的另一种可读性更强的ViewHolder模式写法

程序员文章站 2022-04-18 13:57:52
...

常见的写法是这样的:

@Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder viewHolder;
                
                if( convertView == null ) {
                    convertView = getLayoutInflater().inflate( R.layout.line, null );
                    ImageView imageView = (ImageView) convertView.findViewById( R.id.imageView );
                    TextView textView = (TextView) convertView.findViewById( R.id.textView );
                    viewHolder = new ViewHolder();
                    viewHolder.imageView = imageView;
                    viewHolder.textView = textView;
                    convertView.setTag( viewHolder );
                } else {
                    viewHolder = (ViewHolder) convertView.getTag();
                }

                viewHolder.imageView.setImageResource( R.drawable.ic_launcher );
                viewHolder.textView.setText( arr[ position ] + "");
                return convertView;
            }

但是可读性不好,convertView怎么会当成getView的返回值呢?所以以下是一种更好的写法:

@Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder viewHolder;
                if( convertView == null ) {
                    View view = getLayoutInflater().inflate( R.layout.line, null );
                    ImageView imageView = (ImageView) view.findViewById( R.id.imageView );
                    TextView textView = (TextView) view.findViewById( R.id.textView );
                    viewHolder = new ViewHolder();
                    viewHolder.imageView = imageView;
                    viewHolder.textView = textView;
                    view.setTag( viewHolder );
                    viewHolder.imageView.setImageResource( R.drawable.ic_launcher );
                    viewHolder.textView.setText( arr[ position ] + "");
                    return view;
                } else {
                    viewHolder = (ViewHolder) convertView.getTag();
                    viewHolder.imageView.setImageResource( R.drawable.ic_launcher );
                    viewHolder.textView.setText( arr[ position ] + "");
                    return convertView;
                }
            }

 

因为convertView只是指向一块内存区域,它保存着已显示过的View。只有ListView没超出屏幕时,convertView才为空。如果超出了,convertView就有东西了。

附:ViewHolder如下:

class ViewHolder {
        TextView textView;
        ImageView imageView;
    }