12

I'm building a chat-like application that displays text the user inputs to the screen using a scrollview. What I'm doing is auto-scrolling the scrollview down as more text is appended to the screen. I'm using

 ScrollView my_scrollview = (ScrollView) findViewById(R.id.scroller);
 my_scrollview.fullScroll(ScrollView.FOCUS_DOWN);

This seems to work, although for some reason, because the keyboard is usually on screen while chatting, when the scrollview scrolls down it doesn't completely - the newest textview added is not displayed (you'll have to manually scroll down to the newest one). How do I go about fixing this?

Piotr Chojnacki
  • 6,837
  • 5
  • 34
  • 65
Malfunction
  • 1,324
  • 4
  • 15
  • 25

4 Answers4

41

I looked around, and found that some other people have run into the same problem.

I solved this problem using this piece of code:

final ScrollView scrollView = (ScrollView) findViewById(R.id.scroll_view);
scrollView.post(new Runnable() {
    public void run() {
        scrollView.fullScroll(View.FOCUS_DOWN);
    }
});

Hopefully this can help somebody out there!

Malfunction
  • 1,324
  • 4
  • 15
  • 25
  • 2
    Did not work at first, then used "postDelayed" as suggested in a comment to the other answer. – G B Nov 02 '16 at 12:05
15

Its late but may help some one with this issue.. It takes around 200 miniseconds to add the last element and update it for a scrollView so this will surely work.

void scrollDown()
{
    Thread scrollThread = new Thread(){
        public void run(){
            try {
                sleep(200);
                ChatActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        myScrollView.fullScroll(View.FOCUS_DOWN);
                    }    
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    scrollThread.start();
}

Just call scrollDown(); after adding element to scrollView.

parveen
  • 1,939
  • 1
  • 17
  • 33
2

Did it this way on Xamarin Android project:

var scrollView = FindViewById<ScrollView>(Resource.Id.scrolview); 

scrollView.Post(() =>
{
    scrollView.FullScroll(FocusSearchDirection.Down);
});

Thanks to OP.

0
        @Override
        public void onClick(View v) {

            scview_ashora = findViewById(R.id.scview_ashora);
            scview_ashora.fullScroll(ScrollView.FOCUS_DOWN);

            scview_ashora.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //replace this line to scroll up or down
                    scview_ashora.fullScroll(ScrollView.FOCUS_DOWN);
                }
            }, 1000000L);


        }
    });
  • 2
    Welcome to SO! Code-only answers are discouraged here, as they provide no insight into how the problem was solved. Please update your solution with an explanation of how your code solves the problem at hand :) – Joel Oct 17 '18 at 20:21