我在NestedScrollView中有一个自定义视图。每次在视图上调用invalidate时,布局都会滚动到自定义视图的顶部。我希望重绘视图后滚动位置不变。知道如何做到这一点?
我尝试组合实现onScrollChangeListener和onGlobalLayoutListener以重新滚动到之前滚动的位置,但它不起作用。我在片段的onCreateView方法中有以下代码。
ViewTreeObserver observer = layoutView.getViewTreeObserver();
if (scrollListener != null) {
observer.removeOnScrollChangedListener(scrollListener);
} else {
scrollListener = new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
scrollX = layoutView.getScrollX();
scrollY = layoutView.getScrollY();
}
};
}
observer.addOnScrollChangedListener(scrollListener);
if (layoutListener != null) {
observer.removeOnGlobalLayoutListener(layoutListener);
} else {
layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (customView != null && scrollY != 0 && getUserVisibleHint()) {
layoutView.setVerticalScrollbarPosition(scrollY);
}
};
}
observer.addOnGlobalLayoutListener(layoutListener);
以下是自定义视图的onDraw和onMeasure方法的代码。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (pieces == null) {
return;
}
int position = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols && position < pieces.length; c++) {
Paint paint = (pieces[position] ? complete : empty);
int left = c * stepSize + borderSize + margin;
int right = left + stepSize - borderSize * 2;
int top = r * stepSize + borderSize;
int bottom = top + stepSize - borderSize * 2;
canvas.drawRect(left + borderSize, top + borderSize,
right + borderSize, bottom + borderSize, paint);
++position;
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
cols = width / stepSize;
rows = (int) Math.ceil((float) cells / (float) cols);
margin = (width - cols * stepSize) / 2;
int height = rows * stepSize;
setMeasuredDimension(width, Math.max(width, height));
}