GridView按位置获取视图,第一个子视图不同 [英] GridView get view by position, first child view different
问题描述
Android GridView
很有趣,它重用了子视图.向上滚动的那些从底部回来.所以 GridView
没有方法通过它的位置来获取子视图.但我真的需要了解它的位置并对其进行一些工作.为此,我创建了一个 SparseArray
并从 BaseAdapter
的 getView
中按它们在其中的位置放置视图.
Android GridView
is quite interesting, it reuses the child views. The ones scrolled up comes back from bottom. So there is no method from GridView
to get the child view by its position. But I really need to get view by its position and do some work on it. So to do that, I created an SparseArray
and put views by their position in it from getView
of BaseAdapter
.
SparseArray<View> ViewArray = new SparseArray<View>();
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null)
view = li.inflate(layoutID, null);
ViewArray.put(position, view);
}
现在,我可以通过它们的位置获得所有可见的视图.一切正常,但在某些设备中,第一个子视图(位置 0)与数组中的不同.我记录了 getView
并发现对于位置 0,getView
被多次调用,每次数组都设置为不同的视图.我不知道为什么 GridView 多次为位置 0 调用 getView
并且这种情况只发生在少数设备上.有什么解决办法吗?
Now, I can get all visible views by their position. Everything works perfect as it should but in some devices, the first child view(position 0) is not same as the one in array. I logged the getView
and found that for position 0, getView
got called many times and each time array was set with different view. I have no idea why GridView is calling getView
for position 0 many times and that happens only on few devices. Any solution ?
推荐答案
阅读getPositionForView
的源码后,我在自己的GridView中写了这个方法,API 18完美运行
After reading source of getPositionForView
, I have wrote this method in own GridView, works perfect by API 18
public View GetViewByPosition(int position) {
int firstPosition = this.getFirstVisiblePosition();
int lastPosition = this.getLastVisiblePosition();
if ((position < firstPosition) || (position > lastPosition))
return null;
return this.getChildAt(position - firstPosition);
}
这篇关于GridView按位置获取视图,第一个子视图不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!