Android 解决ListView、GridView在首次显示时adapter可能多次调用getView的问题

    xiaoxiao2021-12-14  22

    当ListView、GridView没有指定具体宽高或没在xml中设置match_parent,可能引起这个问题

    我在TV开发时,以代码设置了LayoutParams的宽高为:MATCH_PARENT,居然也有这个问题

    一般认为引发的原因:容器高度未知,要通过measure子views才知道。

    所以会多次触发onMeasure、onLayout,而draw是在测量、定位都结束之后才进行的

    解决方法:

    > 重写ListView或GridView,并:

    private boolean mIsOnMeasure; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { mIsOnMeasure = true; super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { mIsOnMeasure = false; super.onLayout(changed, l, t, r, b); } public boolean isOnMeasure() { return mIsOnMeasure; } > 在adapter#getView()中判断

    public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; /* 省略convertView与holder的相关代码 在数据填充前,使用以下代码 */ if (parent instanceof MyListView) { if (((MyListView) parent).isOnMeasure()) { return convertView; } } }

    参考:http://blog.csdn.net/kesenhoo/article/details/7196920

    转载请注明原文地址: https://ju.6miu.com/read-971956.html

    最新回复(0)