//很多情况下会有position错位的各种问题。
//when view is recycled by listview, need to catch exception
private ViewHolder getViewHolderByView(View view) {
try {
final <strong>int position = listView.getPositionForView(view);</strong>
if (position == ListView.INVALID_POSITION) {
return null;
}
return getViewHolderByView(position);
} catch (NullPointerException e) {
}
return null;
}
private ViewHolder getViewHolderByView(int position) {
<strong>int wantedPosition = position - listView.getHeaderViewsCount();</strong>
int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount();
int wantedChild = wantedPosition - firstPosition;
if (wantedChild < 0 || wantedChild >= listView.getChildCount()) {
return null;
}
View wantedView = listView.getChildAt(wantedChild);
ViewHolder holder = (ViewHolder) wantedView
.getTag(R.drawable.ic_launcher + getItemViewType(wantedPosition));
return holder;
}
int position = listView.getPositionForView(view);得到当前position在listView中的位置。
<pre name="code" class="java">int wantedPosition = position - listView.getHeaderViewsCount();//如果有headerView的时候减去它的数量得到position。
<pre name="code" class="java">int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount();//由于View复用的问题,要取得当前可见的第一个position(减去headView的数量)。
<pre name="code" class="java">int wantedChild = wantedPosition - firstPosition;//用真实的position减去当前可见的第一个position得到的position才是真正的选中View所在的position。