androidscroller

Confused about the scrollTo(int x,int y) method in Android


There is a scrollTo(int x,int y) method in the View class,but I don't know why the view scroll to the left only when the number of x is positive and negetive the view scroll to right. I thought just the opposite. I'm not a native speaker,Sorry for my poor english! thanks in advance!!


Solution

  • The direction of the scroll is not related to the sign of the x parameter for the scrollTo method.

    This is your x axis:

    <------------------------------------------------------------->
       |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
      -7   -6  -5  -4  -3  -2  -1  0   1   2   3   4   5   6   7
    

    The scrollTo(int x, int y) method will scroll your View to a specific position.

    Let's say the current x position of your View is 3. If you do this:

    scrollTo(1, 0);
    

    You make the View scroll to the right, because the current value of x (3) is greater than the expected value (1).

    Now, if you do this:

    scrollTo(5, 0);
    

    You make the view scroll to the left because the current value of x (3) is lower than the expected value (5).

    To make it simple, the direction of the scroll for the scrollTo method only depends on the difference between the current and the expected values:

    However, the reasoning that you had is correct for the scrollBy(int x, int y) method.

    EDIT

    Here is a more detailed explanation.

    Let's say, again, that your View's current x value is 3. It means that the left border of your screen (for example) matches with the 3 value on the x axis, it can be seen as below:

    <------------------------------------------------------------->
       |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
      -7   -6  -5  -4  -3  -2  -1  0   1   2   3   4   5   6   7
                                               ^
                                               |
                                          LEFT BORDER
    

    Then you want to put your View to 7 on the x axis, it means that you want to put the value 7 to the left border of your screen:

    <------------------------------------------------------------->
       |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
      -7   -6  -5  -4  -3  -2  -1  0   1   2   3   4   5   6   7
                                               ^               ^
                                               |               |
                                          LEFT BORDER       EXPECTED
    

    The LEFT BORDER can't move as it is the left border of your screen. So the only solution is to move the EXPECTED position to the left. It's the same when the expected value is lower than the current one.

    It's pretty complicated to explain this easily, hope you'll get it.