当您对 ScrollView 进行一些更改时,它需要一段时间才能将布局更改复制到显示列表并通知 ScrollView 它确实可以滚动到某个位置。
我设法通过ScrollView
使用我自己的 ScrollView 进行扩展,并添加一个OnGlobalLayoutListener
根据需要添加(如 MH 建议的)并稍后滚动到那里的方法来使其工作。它比将其应用于您需要的每个案例要自动化一些(但是您需要使用 new ScrollView
)。无论如何,这是相关的代码:
public class ZScrollView extends ScrollView {
// Properties
private int desiredScrollX = -1;
private int desiredScrollY = -1;
private OnGlobalLayoutListener gol;
// ================================================================================================================
// CONSTRUCTOR ----------------------------------------------------------------------------------------------------
public ZScrollView(Context __context) {
super(__context);
}
public ZScrollView(Context __context, AttributeSet __attrs) {
super(__context, __attrs);
}
public ZScrollView(Context __context, AttributeSet __attrs, int __defStyle) {
super(__context, __attrs, __defStyle);
}
// ================================================================================================================
// PUBLIC INTERFACE -----------------------------------------------------------------------------------------------
public void scrollToWithGuarantees(int __x, int __y) {
// REALLY Scrolls to a position
// When adding items to a scrollView, you can't immediately scroll to it - it takes a while
// for the new addition to cycle back and update the scrollView's max scroll... so we have
// to wait and re-set as necessary
scrollTo(__x, __y);
desiredScrollX = -1;
desiredScrollY = -1;
if (getScrollX() != __x || getScrollY() != __y) {
// Didn't scroll properly: will create an event to try scrolling again later
if (getScrollX() != __x) desiredScrollX = __x;
if (getScrollY() != __y) desiredScrollY = __y;
if (gol == null) {
gol = new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int nx = desiredScrollX == -1 ? getScrollX() : desiredScrollX;
int ny = desiredScrollY == -1 ? getScrollY() : desiredScrollY;
desiredScrollX = -1;
desiredScrollY = -1;
scrollTo(nx, ny);
}
};
getViewTreeObserver().addOnGlobalLayoutListener(gol);
}
}
}
}
对我来说非常有用,因为我想在添加后立即滚动到 ScrollView 内的给定视图。