获取相对于父级ScrollView的视图坐标

问题描述 投票:5回答:2

[以前,我有以下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 0LinearLayout 1getHitRect。关于Info View 4-6,我需要考虑LinearLayout 0LinearLayout 2getHitRect

事物看起来很麻烦。我有什么办法可以获取相对于最顶部ScrollView的视图坐标?

以前,我具有以下ScrollView和布局。其滚动直到选中的视图可见代码起作用。 [[[

android
2个回答
9
投票
这是当前可行的代码。麻烦。但目前它起作用。我有一些观察。

0
投票
不确定此功能是否在2013年可用,您现在可以像这样进行:
© www.soinside.com 2019 - 2024. All rights reserved.