关于listview的baseadapter的convertView复用问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_25136209/article/details/68958719

这个适配器应该是初学的时候用的最多的了吧
这里主要讲的四个方法getView中的convertView的复用

public View getView(int position, View convertView, ViewGroup parent) {
            View inView=null;
            if (convertView==null) {
                inView = View.inflate(getApplicationContext(), R.layout.item_pm, null);
            }else {
                inView=convertView;
            }
            //下面的不用管,但是fndviewbyid中只要写上View的返回值!!!
            ProcessInfo processInfo = mInfos.get(position);


            TextView textView = (TextView)inView. findViewById(R.id.tv_name);
            TextView textView2=(TextView)inView. findViewById(R.id.tv_mem);
            ImageView imageView=(ImageView)inView. findViewById(R.id.iv_icon);
            CheckBox checkBox=(CheckBox)inView. findViewById(R.id.cb_select);

            textView.setText(processInfo.name);
             textView2.setText("占用内存:"
                     + Formatter.formatFileSize(getApplicationContext(),
                     processInfo.MemSize));
                     // 图标....
                     imageView.setImageDrawable(processInfo.icon);
            return inView;
        }

以上是第一种写法,下面是第二种写法

public View getView(int position, View convertView, ViewGroup parent) {
            //注意这里的区别!!!!!,
            /**
            *这里没有让填充器等于另一个view对象,而是直接判断converview是不是为空,
            *其实结果都是一样的,上面是先弄了一view的变量,当convertView为空的时候
            *给这个view赋值,不为空的时候,让view的值等于这个convertView.其实这个写法和
            *上面的写法都是一样的!!
            *
            */

             if (convertView == null) {
             convertView = View.inflate(getApplicationContext(), R.layout.item_pm, null);
             }


             // 取出控件
             TextView tvName = (TextView)
             convertView.findViewById(R.id.tv_name);
             TextView tvMem = (TextView)
             convertView.findViewById(R.id.tv_mem);
             ImageView ivIcon = (ImageView) convertView
             .findViewById(R.id.iv_icon);
             CheckBox cbSelect = (CheckBox) convertView
             .findViewById(R.id.cb_select);
             // 赋值
             // ProcessInfo processInfo = mInfos.get(position);
             ProcessInfo processInfo = getItem(position);

             tvName.setText(processInfo.name);
             tvMem.setText("占用内存:"
             + Formatter.formatFileSize(getApplicationContext(),
             processInfo.MemSize));
             // 图标....
             ivIcon.setImageDrawable(processInfo.icon);
             return convertView;
             }

上面的两种写法都运行!!!

猜你喜欢

转载自blog.csdn.net/sinat_25136209/article/details/68958719
今日推荐