Android scrollview to scroll up automatically when available space fill so as to show last item

StackOverflow https://stackoverflow.com/questions/23186080

  •  06-07-2023
  •  | 
  •  

Question

I dynamically add the views in the scroll view and I want the scroll view to auto scroll up so as to show last items when available space completely fill.

Was it helpful?

Solution

Your solution is working, but I have also found the following code:

ScrollView scrollView = (ScrollView) findViewById(R.id.sscroll);
scrollView .fullScroll(View.FOCUS_DOWN);

OTHER TIPS

You can tell the scroll view to scroll to a specific place using scrollTo(x,y). However you want to make sure you don't do it on the main thread since the main thread does its operations in order. So that means sometimes you'll have to wait. Therefore you can do it in a background thread.

view.post(new Runnable() {
    @Override
    public void run() {
         scrollView.scrollTo(0, view.getTop());
    }
};

You can achieve this with smoothScrollTo(int x, int y) method. It allows 2 parameters:

x: the position where to scroll on the X axis
y: the position where to scroll on the Y axis

Then, using the y parameter, you will be able to autoscroll the ScrollView when you'll calculate the height of the first child container (generally LinearLayout). Or you can use, as @KieronPapps said, the getTop() method to retrieve the value of top position of this view relative to its parent (in pixels).

However, to autoscroll directly at the start of the Activity, the getTop() will return null because the UI has not the time to be displayed. Then, to avoid the null value, in an Activity, you will need to do your autoscroll inside onWindowFocusChanged(boolean hasFocus) as follows:

@Override
public void onWindowFocusChanged(boolean hasFocus){
    super.onWindowFocusChanged(hasFocus);
    if(hasFocus){
        // do smoothScrollTo(...);
    }
}  

Inside a Fragment a simple Runnable will do the same. I have written an answer on a similar behaviour, it might help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top