在ScrollView中动态滚动相对布局

3

我有一个滚动视图,在其中有几个相对布局。每个相对布局会动态添加两个按钮。如下所示:

滚动视图

  _____________________
 |   ________________  |
 |  |Relative Layout|  |
 |  |   |Buttons|   |  |
 |  |_______________|               
 |                     |
 |   ________________  |
 |  |Relative Layout|  |
 |  |   |Buttons|   |  |
 |  |_______________|                 
 |                     |
 |  |Relative Layout|  |
 |  |   |Buttons|   |  |
 |  |_______________|               
 |                     |
 |   ________________  |
 |  |Relative Layout|  |
 |  |   |Buttons|   |  |
 |  |_______________|                  
 |                     |
 |  |Relative Layout|  |
 |  |   |Buttons|   |  |
 |                     |
 |_____________________|

在按钮点击时,动态地滚动到特定的相对布局是否可能?我已经尝试了下面的代码,但没有成功。
if (count == 1) {
    final int k = id;
mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(
        new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
                public void onGlobalLayout() {
            // TODO Auto-generated
        // method stub
        mScrollView.post(new Runnable() {
                @Override
            public void run() {
            Button btn = (Button) findViewById(k);
            mScrollView.smoothScrollTo(0,btn.getTop());
                }
        });

滚动也不起作用

编辑: 最初我只在相对布局中有一组按钮,然后smoothScrollTo按预期工作。后来我将结构更改为上述样式。


2
欢迎来到stackoverflow,下次请添加格式良好的代码。 - DroidDev
你有这个布局的XML布局吗?你能也发布一下吗? - Satyaki Mukherjee
我正在XML中创建以下滚动视图:<ScrollView android:id="@+id/scroll_view" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="88" />并且在上述代码中,我正在动态添加相对布局。 - Biplab
3
请在编辑您的帖子时添加代码,而不是在评论中附加它。此外,btn.getTop()不会返回相对于屏幕的位置,而是相对于其父视图的位置。因此,我认为您想要其父视图即相邻的RelativeLayout的位置信息。 - Daniel Bo
1个回答

5

@Daniel Bo的提示是正确的。

view.getTop()将给出相对于其直接父级的位置。

以下是实现。

ScrollView mScrollView = (ScrollView) findViewById(R.id.scroll_view);
mScrollView.post(new Runnable() {
    public void run() { 
        Button btn = (Button) findViewById(k); 
        ViewGroup vg =(ViewGroup)btn.getParent();
        mScrollView.smoothScrollTo(0,vg.getTop());
     }});
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接