TheBrillowable
TheBrillowable

Reputation: 319

How to keep a ScrollView to be scrolled to the Bottom?

I have a ScrollView with a LinearLayout inside an I'm adding TextViews. But I always want the last added TextView to be visible, so I need the ScrollView to scroll to the Bottom, when a TextView is added. I don't know why, but when I call scrollto(), scrollby() or fullScroll() after adding a textview, it only scrolls to the textview before the last one.

Do you know a better way to do this?

Thanks a lot!

Code:

I got a Button, which calls this function:

private void addRound() {
    // TODO Auto-generated method stub
    TextView newRound = new TextView(Stopwatch.this);
    newRound.setText("" + counter + ". - " + timerText());
    newRound.setTextSize(20);
    newRound.setGravity(Gravity.CENTER);
    linlay.addView(newRound);
    counter++;
}

After calling this function I call fullScroll().

addRound();
sv.fullScroll(View.FOCUS_DOWN);

sv ist my ScrollView, linlay is the linearlayout inside the scrollview.

Upvotes: 6

Views: 3931

Answers (2)

butoff
butoff

Reputation: 1

Another approach is to use ViewTreeObserver.OnGlobalLayoutListener. Add this code snippet in onCreate() method.

    linlay.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            sv.fullScroll(View.FOCUS_DOWN);
        }
    });

Upvotes: 0

Henry Thompson
Henry Thompson

Reputation: 2481

I reckon it's because the ScrollView is not quite updated by the time you call sv.scrollFull(View.FOCUS_DOWN); Try the following (to replace your second code sample):

addRound();
sv.post(new Runnable() {

   @Override
   public void run() {
     sv.fullScroll(View.FOCUS_DOWN);
   }
});

If the above doesn't work, try the following (it's not an elegant way of doing it but it may work):

addRound();
sv.postDelayed(new Runnable() {

   @Override
   public void run() {
     sv.fullScroll(View.FOCUS_DOWN);
   }
}, 100);

Hope this works!

Upvotes: 11

Related Questions