How to keep the scroll scroll at the bottom?

I have a ScrollView with LinearLayout inside I'm adding TextViews. But I always want the last TextView added 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 the text to the last.

Do you know the best way to do this?

Thanks a lot!

the code:

I have a button that 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 linear output inside the scroll.

+6
source share
2 answers

I consider this because ScrollView is not completely updated by the time sv.scrollFull(View.FOCUS_DOWN); Try the following (to replace the second code sample):

 addRound(); sv.post(new Runnable() { @Override public void run() { sv.fullScroll(View.FOCUS_DOWN); } }); 

If the above does not work, try the following (this is not an elegant way to do this, but it may work):

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

Hope it works!

+11
source

Another approach is to use ViewTreeObserver.OnGlobalLayoutListener. Add this piece of code to the onCreate () method.

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

Source: https://habr.com/ru/post/907792/


All Articles