在Android ScrollView类中使用smoothScrollBy方法

Dav*_*lin 5 android scrollview

我有一个带有ScrollView的Android程序,当我在计算机上的模拟器上调用scrollBy方法时,它将正确地进行自动滚动,但不能在我的Android手机上执行.

这是代码:

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);
}
}
Run Code Online (Sandbox Code Playgroud)

此外,常规scrollBy方法不起作用或scrollTo方法(虽然我可能没有正确使用它,因为它也不能在计算机上工作).有谁知道什么可能是错的?

编辑:

Darrell的答案显示我的问题是我在一个函数中调用了我的smoothScrollBy方法,我在这个函数中更改了布局,使得滚动区域足够大,可以滚动.显然,当我在函数中调用它时,实际上没有应用更改,因此无法滚动.

因此,我使用他的建议更改了代码:

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.
}
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*ell 8

你是否从onCreate方法调用smoothScrollBy?尝试等待,直到设置视图,例如从onResume.(如果必须从onCreate执行此操作,则可以使用OnGlobalLayoutListener为视图注册ViewTreeObserver,并从那里进行滚动.)