GridView Adapter里的getView为啥会多次调用position 0
一、问题描述
GridView Adapter里的getView方法总会调用很多次的position 0
图中的GridView 包含9个大小相同的itemView,区别在于itemView中包含的textView中的文字不同。
二、问题分析
getView方法
既然是getView引起的,我们就先从这个方法本身入手,看看这里到底干了啥?
首先,我们知道
The Adapter provides access to the data items.
The Adapter is also responsible for making a View for each item in the data set.
那么getView呢?
顾名思义,就是得到一个View用来展示在数据集中特定位置的数据。所以我们需要再往上找,看看是它是怎么被调用的?
onMeasure方法
接下来,我们需要找的就是GridView,阅读GridView源码时,我们主要关注以下3个方法:onMeasure、onLayout、onDraw,那么我们先来看下onMeasure。
- onMeasure是干啥的? 这里我们要追溯到View的measure方法:计算出一个view的大小,而它实际的计算工作是由它的子类重写onMeasure方法来实现。
- 具体源码解析
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Sets up mListPadding
// MeasureSpec 是父View对子View大小的期望:包括测量模式、测量大小
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// codes about measuring childWidth and child height
mItemCount = mAdapter == null ? 0 : mAdapter.getCount();

本文分析了GridView Adapter中的getView方法为何会被多次调用position 0的问题。通过对onMeasure方法的深入研究,揭示了在计算视图大小过程中导致此现象的原因,并探讨了GridView的布局流程。提出了两种解决办法,包括在getView中添加判断以及期待更多的解决方案。参考文章提供了更深入的了解。
最低0.47元/天 解锁文章
908

被折叠的 条评论
为什么被折叠?



