ListView 重设Adapter后的动作,remove/add ListView 的动作

Adapter adapter1

//设置adapter1,会创建屏幕可见多个的ItemView

ListView.setAdapter(adapter1);

//设置adapter为null,则上面创建的缓存ItemViews都会被清除(每个ItemView都调用了 onDetachedFromWindow)

ListView.setAdapter(null);

//再设置回adapter1,会重新创建所有的ItemView,之前的都舍弃了,每个View的hashCode都不一样了

ListView.setAdapter(adapter1);

即使每次重复设置同一个adapter,也会将之前的View全部清除,重新创建

 public void setAdapter(ListAdapter adapter) {
if (mAdapter != null && mDataSetObserver != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
} //调用 removeAllViewsInLayout() 移除了所有的childview
resetList(); //复用的view也清除了
mRecycler.clear(); // 如果有headerView或者footerView,要对adapter包装一层
if (mHeaderViewInfos.size() > 0|| mFooterViewInfos.size() > 0) {
mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter);
} else {
mAdapter = adapter;
} mOldSelectedPosition = INVALID_POSITION;
mOldSelectedRowId = INVALID_ROW_ID; // AbsListView#setAdapter will update choice mode states.
super.setAdapter(adapter); //....... // 重新布局
requestLayout();
}

把一个显示好的ListView,调用 removeView 其从父View中将其移除,然后再用 addView 重新添加到父View中,

之前创建好的 子View会复用,不会重新创建,但是ListView的滚动条位置信息丢失了,会显示到第一行去。

getView: == null 0
MyImg onAttachedToWindow:1106635464

getView: == null 1
MyImg onAttachedToWindow:1106667456

getView: == null 2
MyImg onAttachedToWindow:1106668496

getView: == null 3
MyImg onAttachedToWindow:1106669536

-----对ListView的父View调用 removeAllView()-----
MyImg onDetachedFromWindow:1106635464
MyImg onDetachedFromWindow:1106667456
MyImg onDetachedFromWindow:1106668496
MyImg onDetachedFromWindow:1106669536

-----addView(ListView list)重新添加到父View中-----
MyImg onAttachedToWindow:1106635464
MyImg onAttachedToWindow:1106667456
MyImg onAttachedToWindow:1106668496
MyImg onAttachedToWindow:1106669536

getView: != null 0
getView: != null 1
getView: != null 2
getView: != null 3

上一篇:CSS水平垂直居中的方法


下一篇:c#读properties文件