I have a ScrollView that contains elements with visibility set to View.GONE by default. The problem is that whenever this visibility changes from View.GONE to View.VISIBLE, scroll jumps up as it is shown on second picture: https://i.imgur.com/WmRc4M2.png
The red box represents current scroll position, blue rectangle is an element which visibility is changed, and green rectangle is some element (for example button) that I can refer to. I want my ScrollView to work as it is shown on third picture. If green button is on the screen, it should also be visible on screen after displaying new element (the blue one) above it. Any ideas how can I achieve it?
Advertisement
Answer
well, it behaves exacly as it should – scroll position is on e.g. 200px from top and this doesn’t change when new item changes its visibility
you should scroll by yourself to proper (new) point, use scrollTo method – measure height of this new View
and call scrollView.scrollTo(0, currentScrollY + heightOfNewView)
be aware that when you change visibility then you can’t call above scrollTo
just one line below, you have to wait for this View
being measured and drawn. so you should call scrollTo
in e.g.
visibilityChangedView.setVisibility(View.VISIBLE); visibilityChangedView.post(new Runnable() { // this will be called when visibilityChangedView won't have // any pending tasks to do, but we just changed visibility, // so at first view will be measured and drawn, after that // below run() method will be called @Override public void run() { int heightOfNewView = visibilityChangedView.getMeasuredHeight(); int currentScrollY = scrollView.getScrollY(); scrollView.scrollTo(0, currentScrollY + heightOfNewView); } );
there is a chance that this automatic scroll will be visible to user as quick jump – at first whole view will be drawn as #2 and after split second/one frame it will redraw at new position like #3. I don’t know how your content is built (rest of childs in Scrollview
), but I suspect that this should be RecyclerView
or at least ListView
with proper Adapter
, not ScrollView
with fixed layout