[以前,我有以下ScrollView
和布局。其滚动直到选中的视图可见代码起作用。
<ScrollView>
<LinearLayout>
<Info View 1/>
<Info View 2/>
<Info View 3/>
</LinearLayout>
</ScrollView>
private void initScrollView() {
if (this.selectedInfoView == null) {
// Nothing to scroll.
return;
}
ScrollView scrollView = (ScrollView)this.getView().findViewById(R.id.scrollView);
Rect rect = new Rect();
Rect scrollViewRect = new Rect();
selectedInfoView.getHitRect(rect);
scrollView.getDrawingRect(scrollViewRect);
int dy = rect.bottom - scrollViewRect.bottom;
if (dy > 0) {
scrollView.scrollBy(0, dy);
}
}
注意,getHitRect
将返回上一级父级的坐标。因此,以上代码将起作用。
但是,涉及到稍微复杂的情况。上面的代码不再起作用。
<ScrollView>
<LinearLayout 0>
<TextView/>
<LinearLayout 1>
<Info View 1/>
<Info View 2/>
<Info View 3/>
</LinearLayout>
<TextView/>
<LinearLayout 2>
<Info View 4/>
<Info View 5/>
<Info View 6/>
</LinearLayout>
</LinearLayout>
</ScrollView>
在我的代码中,如果遇到Info View 1-3,则需要考虑LinearLayout 0和LinearLayout 1的getHitRect
。关于Info View 4-6,我需要考虑LinearLayout 0和LinearLayout 2的getHitRect
。
事物看起来很麻烦。我有什么办法可以获取相对于最顶部ScrollView
的视图坐标?
以前,我具有以下ScrollView和布局。其滚动直到选中的视图可见代码起作用。