• ListView优化


    在getView()方法中,每次都将布局重新加载了一遍,当ListView快速滚动的时候,这就会成为性能的瓶颈。

    getView()方法中还有一个convertView参数,这个参数用于将之前加载好的布局进行缓存,以便之后可以进行重用。

    因此我们可以通过他来进行优化:

     @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Fruit fruit = getItem(position);
            View view;
            if (convertView == null) {
                view = LayoutInflater.from(getContext()).inflate(resourceId, parent,
                    false);
            } else {
                view = convertView;
            }
            ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
            TextView fruitName = (TextView) view.findViewById(R.id.fruit_name);
            fruitImage.setImageResource(fruit.getImageId());
            fruitName.setText(fruit.getName());
            return view;
        }

    不过,目前我们的这份代码还是可以继续优化的,虽然现在已经不会再重复去加载布局,但是每次在getView()方法中还是会调用ViewfindViewById()方法来获取一次控件的实例。我们可以借助一个ViewHolder来对这部分性能进行优化:

     @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Fruit fruit = getItem(position);
            View view;
            ViewHolder viewHolder;
            if (convertView == null) {
                view = LayoutInflater.from(getContext()).inflate(resourceId, parent,
                false);
                viewHolder = new ViewHolder();
                viewHolder.fruitImage = (ImageView) view.findViewById
                (R.id.fruit_image);
                viewHolder.fruitName = (TextView) view.findViewById (R.id.fruit_name);
                view.setTag(viewHolder); // 将ViewHolder存储在View中
            } else {
                view = convertView;
                viewHolder = (ViewHolder) view.getTag(); // 重新获取ViewHolder
            }
            viewHolder.fruitImage.setImageResource(fruit.getImageId());
            viewHolder.fruitName.setText(fruit.getName());
            return view;
        }
    
        class ViewHolder {
    
            ImageView fruitImage;
    
            TextView fruitName;
    
        }
  • 相关阅读:
    【codeforces 411B】Multi-core Processor
    【codeforces 314C】Sereja and Subsequences
    【hdu 1890】Robotic Sort
    【图灵杯 A】谷神的赌博游戏
    【图灵杯 J】简单的变位词
    【图灵杯 F】一道简单的递推题(矩阵快速幂,乘法模板)
    【图灵杯 E也即POJ 3368】简单的RMQ
    【codeforces 496E】Distributing Parts
    【codeforces 553C】Love Triangles
    Diffie-Hellman Key Exchange – A Non-Mathematician’s Explanation
  • 原文地址:https://www.cnblogs.com/lvcoding/p/8286768.html
Copyright © 2020-2023  润新知