上周调试一个bug,最终问题定位到了
mCurPlayItemView = mListview.getChildAt(mCurPos + mListview.getHeaderViewsCount() - mListview.getFirstVisiblePosition());这句代码中。mCurPos为当
前position,mCurPlayItemView为当前position所对应的itemView。当mCurPos不在屏幕可见范围内,会导
致获取的mCurPlayItemView为null,这是由于listView的回收机制导致的,listView会保证其子view只
会attach在其可见区域内,不可见区域,其子view会被回收掉。
mCurPos保存的是当前可见区域操作的item得position,按理说获取的itemView应该不会为null,但是在屏幕
旋转之后,activity会重新创建,这段这段逻辑随着onCreate的执行而被重新调用,而此时mCurPos指向的
position因为屏幕的旋转,已经不可见了,所以在这种情况下获取的itemView为null
ListView根据position获取ItemView
stackoverflow上有这个的解决方案。
public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition ) {
return listView.getAdapter().getView(pos, null, listView);
} else {
final int childIndex = pos - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
不过这段代码没有算header
第8行代码需要写改下final int childIndex = pos + getHeaderViewsCount() - firstListItemPosition;
RecyclerView根据position获取ItemView
recyclerview中,直接可以通过layoutmanager的View findViewByPosition(int position)获取itemView
和listView一样recyclerview在屏幕不可见的区域获取的itemView也会为null。