Question

I have A scroll view in which i have several relative layouts in it. And a relative Layout has two buttons add to it Dynamically.As below

Scroll View

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

Is it possible to scroll to specific relative layout dynamically on a button click. I have already Tried below and its not working

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());
                }
        });

Scroll to also not working

Edit: Originally I had only a set of buttons in the relative layout. Then smoothScrollTo was working as expected. Later I changed the structure to the above style.

Was it helpful?

Solution

@Daniel Bo's hint was correct.

view.getTop() will give position relative to its immediate parent.

Below is the implementation.

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());
     }});
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top