1

my layout is inside a ScrollView. The id of the element and type of element to which i want to scroll with my search i found code below to do it but i'm not successful in scrolling to the element specific to the id, I have given 0,id as two parameters.

ScrollView sv = (ScrollView) mainActivity.findViewById(R.id.scrollview);
  scrollview.scrollTo(0,id);
praveen
  • 420
  • 4
  • 18

1 Answers1

1

Get the ViewTreeObserver of the ScrollView and add an OnGlobalLayoutListener to the ViewTreeObserver. Then call the ScrollView.scrollTo(x,y) method from the onGlobalLayout() method of the OnGlobalLayoutListener.

 ScrollView mainScroll = (ScrollView) findViewById(R.id.average_scroll_mainScroll);

 ViewTreeObserver vto = scrollView.getViewTreeObserver();
 vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
      public void onGlobalLayout() {
           mainScroll.scrollTo(0, 0);
      }
 });

Source. Courtesy - fahmy :)

However the catch here is that it takes position of the view to scroll to instead of its ID. So you will have to find your views position first and then pass them as parameter to scrollTo. Use the below for getting the position,

View.getLocationOnScreen(int[] location);

this returns an integer array where (x = location[0] and y = location[1]). Here are docs for this method.

Community
  • 1
  • 1
Atul O Holic
  • 6,692
  • 4
  • 39
  • 74
  • k.what should i pass as params to scrollTo directly element id will work? – praveen Feb 21 '14 at 10:22
  • See my edits now and try this one. Let me know how it goes. Also, I found this method getGlobalVisibleRect() here, http://stackoverflow.com/questions/3619693/getting-views-coordinates-relative-to-the-root-layout. Try this in case the first one doesn't suit your need. – Atul O Holic Feb 21 '14 at 10:54
  • but i'm just having id,type of element only with me with these only can't i scroll – praveen Feb 21 '14 at 11:39
  • Yes you can, only thing is you have to combine both the tricks(till I or U or someone else provides the direct way :)). First get the position of your View (x and y) and then call your scrollTo method. Did you try them? – Atul O Holic Feb 21 '14 at 11:44
  • 1
    ScrollView sv = (ScrollView) findViewById(R.id.scrollview); TextView gotoTv = (TextView) findViewById(id); int x = (int) gotoTv.getX(); int y = (int) gotoTv.getY(); sv.scrollTo(x, y); this is how i'm trying and it's not working – praveen Feb 21 '14 at 11:54
  • Please post your gotoTv method. – Atul O Holic Feb 21 '14 at 11:56
  • gotoTv is textview only that i have mentioned in my earlier comment – praveen Feb 21 '14 at 11:57