Android ListView性能提升小技巧

来源:互联网 发布:东吴证券下载软件 编辑:程序博客网 时间:2024/04/29 19:46

虽然现在都推荐Recyclerview来替换ListView,但在实际开发中我们用到ListView的开发者还是居多的。那么不可避免的就是在使用ListView时我们要注意其性能,要对其进行优化的问题也是一个老生常谈的问题了。那么本人就简单说下自己所知道的优化方案吧!

  • 使用ViewHolder,复用缓存资源。

  • Item的布局层次越少越好,避免深层次嵌套。

  • 在快速滑动的时候不加载图片(某些情况下可以不加载数据),停止后在加载。

  • ListView在符合需求的情况下,尽可能设置width和height为match_parent,减少onMeasure的测量时间。(Item也同理)

  • 在adapter中的getview尽量减少逻辑代码的处理。

  • 将ListView的scrollingCache和animationCache设置为false。

  • 尽量大可能的避免GC。

  • 数据量大的时候分页加载数据。

1.使用ViewHolder,复用缓存资源,列如:

优化前:

  @Override    public View getView(int position, View convertView, ViewGroup parent) {        convertView = LayoutInflater.from(mContext).inflate(R.layout.item_layout, parent, false);        ImageView imageView = (ImageView) convertView.findViewById(R.id.img_item);        //这里做一些事件逻辑处理...        return convertView;    }

优化后:

    @Override    public View getView(int position, View convertView, ViewGroup parent) {        ViewHolder mViewHolder = null;        if (convertView == null) {            mViewHolder = new ViewHolder();            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_layout, parent, false);            mViewHolder.mImageView = (ImageView) convertView.findViewById(R.id.img_item);            convertView.setTag(mViewHolder);        } else {            mViewHolder = (ViewHolder) convertView.getTag();        }        //这里做一些事件逻辑处理...        return convertView;    }    private static class ViewHolder {        ImageView mImageView;    }

上面这样的优化,我想只要学习Android开发的都应该知道其原理。如果不知道的,那还是去找找资料吧!这里不做过多解释。

2.Item的布局层次越少越好,避免深层次嵌套。列如:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent">        <ImageView            android:id="@+id/img_item"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:src="@mipmap/ic_launcher"/>    </LinearLayout></LinearLayout>

上面这Item布局,很明显就能看出来外面多嵌套了一层LinearLayout,这就增加了多余的层次嵌套。所以,在ListView的Item布局中,我们也应该利用include,merge,ViewStub这三兄弟去优化复杂的布局。同时避免多余的嵌套而造成的资源浪费,对布局进行合理的布局。

3.在快速滑动的时候不加载图片(某些情况下可以不加载数据),停止后在加载。

这个优化是在ListView中加载网络图片和数据资源时非常有必要的。因为如果我们在快速滑动中去加载网络图片话,会使的ListView变得卡顿,这样就会造成一种非常不好的用户体验。所以,我们需要监听ListView的滑动状态,如果滑动的时候停止加载网络图片或一些特殊的数据;停止滑动的时候,则开启线程取加载资源。

        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {            @Override            public void onScrollStateChanged(AbsListView view, int scrollState) {                if(scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING){                    //快速滑动的时候停止加载图片                }else{                    //停止后开始加载                }            }            @Override            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {            }        });

4.尽可能的设置ListView的布局为match_parent

在Android开发中每个容器View里面,你往里面添加内容它都要去测量一下它的资料。比如高宽什么的。ListView也不例外,看ListView的onMeasure()源码:

    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        // Sets up mListPadding        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);        int widthSize = MeasureSpec.getSize(widthMeasureSpec);        int heightSize = MeasureSpec.getSize(heightMeasureSpec);        int childWidth = 0;        int childHeight = 0;        int childState = 0;        mItemCount = mAdapter == null ? 0 : mAdapter.getCount();        if (mItemCount > 0 && (widthMode == MeasureSpec.UNSPECIFIED                || heightMode == MeasureSpec.UNSPECIFIED)) {            final View child = obtainView(0, mIsScrap);            // Lay out child directly against the parent measure spec so that            // we can obtain exected minimum width and height.            measureScrapChild(child, 0, widthMeasureSpec, heightSize);            childWidth = child.getMeasuredWidth();            childHeight = child.getMeasuredHeight();            childState = combineMeasuredStates(childState, child.getMeasuredState());            if (recycleOnMeasure() && mRecycler.shouldRecycleViewType(                    ((LayoutParams) child.getLayoutParams()).viewType)) {                mRecycler.addScrapView(child, 0);            }        }        if (widthMode == MeasureSpec.UNSPECIFIED) {            widthSize = mListPadding.left + mListPadding.right + childWidth +                    getVerticalScrollbarWidth();        } else {            widthSize |= (childState & MEASURED_STATE_MASK);        }        if (heightMode == MeasureSpec.UNSPECIFIED) {            heightSize = mListPadding.top + mListPadding.bottom + childHeight +                    getVerticalFadingEdgeLength() * 2;        }        if (heightMode == MeasureSpec.AT_MOST) {            // TODO: after first layout we should maybe start at the first visible position, not 0            heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1);        }        setMeasuredDimension(widthSize, heightSize);        mWidthMeasureSpec = widthMeasureSpec;    }

从上面简单的可以了解到,如果我们给ListView设置match_parent会减少测量次数,这样也是可以提升性能的。

5.在adapter中的getview尽量减少逻辑代码的处理

比如:我ListView中的Item我可能要适配某个东西,所以要动态设置。那么,如果像下面这样写:

    @Override    public View getView(int position, View convertView, ViewGroup parent) {        ViewHolder mViewHolder = null;        if (convertView == null) {            mViewHolder = new ViewHolder();            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_layout, parent, false);            mViewHolder.mImageView = (ImageView) convertView.findViewById(R.id.img_item);            convertView.setTag(mViewHolder);        } else {            mViewHolder = (ViewHolder) convertView.getTag();        }        mViewHolder.mImageView.getLayoutParams().height = 80;        mViewHolder.mImageView.getLayoutParams().width = LinearLayout.LayoutParams.MATCH_PARENT;        // 底下写了一大堆逻辑处理的代码        return convertView;    }

getView()会被调用多次,那么设置高度,宽度也会被调用多次。这是不是造成了性能浪费呢!并且如果你getView()里面写了一大堆逻辑代码,可读性也会变差。有可能造成你开发得时候思维混乱,所以getView()里面的逻辑代码我们应该尽量剥离出去,降低耦合性。

优化后:

    @Override    public View getView(int position, View convertView, ViewGroup parent) {        ViewHolder mViewHolder = null;        if (convertView == null) {            mViewHolder = new ViewHolder();            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_layout, parent, false);            mViewHolder.mImageView = (ImageView) convertView.findViewById(R.id.img_item);            mViewHolder.mImageView.getLayoutParams().height = 80;            mViewHolder.mImageView.getLayoutParams().width = LinearLayout.LayoutParams.MATCH_PARENT;            convertView.setTag(mViewHolder);        } else {            mViewHolder = (ViewHolder) convertView.getTag();        }        xxxType();    // 这份方法里面进行逻辑处理        return convertView;    }

6.将ListView的scrollingCache和animationCache设置为false
scrollingCache: scrollingCache本质上是drawing cache,你可以让一个View将他自己的drawing保存在cache中,这样下次再显示View的时候就不用重画了,而是从cache中取出。默认情况下drawing cahce是禁用的,因为它太耗内存了,但是它确实比重画来的更加平滑。而在ListView中,scrollingCache是默认开启的,我们可以手动将它关闭。

animateCache: ListView默认开启了animateCache,这会消耗大量的内存,因此会频繁调用GC,我们可以手动将它关闭掉

不懂的可以查看 http://stackoverflow.com/questions/15570041/scrollingcache 这里进行解答,博主英文不太好,就不进行翻译了。

所以没有特殊情况下,就隐藏这2个选项吧!

   <ListView        android:id="@+id/test_list_view"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:dividerHeight="1dp"        android:divider="@android:color/holo_blue_light"        android:scrollingCache="false"        android:animationCache="false">    </ListView>

7.尽量大可能的避免GC
在android中我们创建大量的对象的时候,GC就会频繁的执行。这时log日志里会频繁的输出”GC has freed some memory …”。所以,在Adapter的getView()中,我们尽量不要创建过多的对象,尽量做到不在ViewHolder以为创建对象。如果你没有创建过多的对象,但还是出现频繁的GC的话,那么重复上面步骤。或者检查你getView()中的数据加载是否有问题(主要是网络图片加载)。

8. 数据量大的时候分页加载数据。
在加载大量数据的时候,不要一次性加载。应该分页,分量加载,主要用于上拉加载的时候。

以上,就是我做开发这点时间里所知道的优化内容,如果上面有什么错误或者您有补充的话,欢迎留言,么么哒! 但是,到了这里我还是推荐大伙去使用Recyclerview。

3 0
原创粉丝点击