我有一个带BaseAdapter的ListView.我想经常更新列表中的一些项目而不刷新内容.为了实现这一点,我正在使用Observer模式.我有一个Observable对象,列表中的每个项目都是一个观察者.
public View getView(final int position, View convertView, final ViewGroup parent) {
final ItemViewHolder holder;
final Item item = (Item) getItem(position);
if (convertView == null) {
convertView = inflater.inflate(R.layout.item, parent, false);
/* ADD VIEWS TO HOLDER */
holder = new ItemViewHolder();
convertView.setTag(holder);
ItemObserver observer = new ItemObserver(holder, context);
mapObservers.put(holder, observer);
observable.addObserver(observer);
} else {
holder = (ItemViewHolder) convertView.getTag();
}
//Set values into view etc...
return convertView;
}
这很好但问题是:我怎么知道不再需要观察者?我想检测给定视图何时被销毁,以便从Map获取观察者并从Observable对象中删除它.在视图被销毁时是否有任何侦听器被调用?
我尝试了AbsListView.RecyclerListener.onMovedToScrapHeap(View view),但是当View被回收时似乎被调用了.
谢谢!
解决方法:
根据this offical issue,onViewDetachFromWindow BUT存在问题
onDetachedFromWindow() will not necessarily be called in this
situation. ListView
children are recycled and reused, and ListView avoids unnecessary
onDetachedFromWindow() whenever possible.
However, onDetachedFromWindow()
should be called for all views created by the adapter when the Activity is destroyed or
when ListView is detached from the window.
所以你不能指望列表视图被销毁.