在检查了ListView
一段时间的源代码后,我设法从ListView.onSizeChanged()
. 关键是在 ListView 实际调整大小后进行滚动。我们可以通过使用post
函数来做到这一点。
这是代码(注意它不会滚动,只是设置正确的位置,但你明白了):
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (mFooterView.getVisibility() == View.GONE) {
mFooterView.setVisibility(View.VISIBLE);
// at this point, the listview's height hasn't changed yet
int listOldHeight = parent.getHeight();
if (mItemAutoVisibilityScroller == null) {
mItemAutoVisibilityScroller = new ItemAutoVisibilityScroller();
}
// allow the list to resize
mFooterView.post(mItemAutoVisibilityScroller.setup(listOldHeight, position, view.getTop(), view.getHeight()));
} else {
mFooterView.setVisibility(View.GONE);
}
}
private class ItemAutoVisibilityScroller implements Runnable {
private int mListOldHeight;
private int mPosition;
private int mItemTop;
private int mItemHeight;
public ItemAutoVisibilityScroller setup(int listOldHeight, int position, int itemTop, int itemHeight) {
mListOldHeight = listOldHeight;
mPosition = position;
mItemTop = itemTop;
mItemHeight = itemHeight;
return this;
}
public void run() {
final int textTop = mFooterView.getTop();
// is the item cut by the footer?
if (mItemTop + mItemHeight > textTop) {
int newItemTop = mListOldHeight - mFooterView.getHeight() - mItemHeight;
if (newItemTop < 0) {
newItemTop = 0;
}
// move the item just above the footer
mListView.setSelectionFromTop(mPosition, newItemTop);
}
}
}