Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using smoothScrollBy method in Android ScrollView class

I have an Android program with a ScrollView that will correctly do an automatic scroll when I call the scrollBy method on the emulator on my computer but will not do it on my Android phone.

Here is the code:

public class RecordGameActivity3 extends Activity {
ScrollView myView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recordgame3);
    myView = (ScrollView)findViewById(R.id.scrollView1);

}

public void addPlayer(View v)
{
    //Removed non-related code

    myView.smoothScrollBy(0, 50);
}
}

Also, the regular scrollBy method doesn't work or the scrollTo method (although I may just not be using that correctly since that doesn't work on the computer either). Does anyone have an idea what might be wrong?

EDIT:

My problem as Darrell's answer showed me was that I was calling my smoothScrollBy method from within a function where I was making changes to the layout that would make the scroll area big enough to be able to be scrolled. Apparently, by the time I was calling it in the function, the changes weren't actually applied and so it couldn't be scrolled.

Thus, I changed the code using his advice to the following:

public class RecordGameActivity3 extends Activity {
ScrollView myView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recordgame3);
myView = (ScrollView)findViewById(R.id.scrollView1);

// New code that listens for a change in the scrollView and then calls the scrollBy method.
ViewTreeObserver vto = myView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    public void onGlobalLayout() {
        myView.smoothScrollBy(0, 100);
    }});

}

public void addPlayer(View v)
{
    //Code that is called on an onClick listener that adds things to the ScrollView making it scrollable.
}
}
like image 217
David Daudelin Avatar asked Mar 17 '12 20:03

David Daudelin


2 Answers

Are you calling smoothScrollBy from the onCreate method? Try waiting until after the views are set up, for instance from onResume. (If you must do it from onCreate you could register a ViewTreeObserver for your view with a OnGlobalLayoutListener, and do the scrolling from there.)

like image 147
Darrell Avatar answered Sep 24 '22 14:09

Darrell


In my case, I need to scroll the ScrollView when there is a MotionEvent.ACTION_UP event triggered in the exact ScrollView , scrollTo() works, but smoothScrollTo() doesn't . Thanks to you guys, I figured it out now, use a handler to smoothScroll the view after a while will work.

like image 40
shenghuadun Avatar answered Sep 21 '22 14:09

shenghuadun