Search code examples
javaandroidandroid-nestedscrollview

How do I scroll down and up in my Nestedscrollview programatically with some delay?


I want to scroll down once and then up programatically. The scrolling should be slow and smooth. This is my code:

scroll_1.post(() -> scroll_1.fullScroll(View.FOCUS_DOWN));
scroll_1.postDelayed(() -> {
    scroll_1.smoothScrollTo(0,0);
},1000);

When I run the code, it scrolls down and up so fast, how do I fix this?


Solution

  • To solve your problem, replace the statement:

    scroll_1.smoothScrollTo(0,0);
    

    with the following:

    ObjectAnimator.ofInt(scroll_1, "scrollY",  SCROLL_TO).setDuration(SCROLL_DURATION).start();
    

    You have to replace SCROLL_TO with the position where you want to scroll to. If you want to scroll to the top, you can put 0 as the value.

    SCROLL_DURATION is the duration in milliseconds that you want the ScrollView to take to scroll to a certain position.

    If you want to scroll to the bottom, then you have to use ScrollView.getBottom(). Example code:

    ObjectAnimator.ofInt(scroll_1, "scrollY",scroll_1.getBottom()).setDuration(SCROLL_DURATION).start();