如何在活动启动时在 ScrollView 中滚动到底部

我正在 ScrollView 中显示一些数据。在活动启动(onCreate 方法)时,我用数据填充 ScrollView,并想滚动到底部。

我试过用 getScrollView().fullScroll(ScrollView.FOCUS_DOWN)。这在我将其作为按钮单击操作时可以工作,但是在 onCreate 方法中不能工作。

有没有办法在活动启动时将 ScrollView 滚动到底部?这意味着视图在第一次显示时已经滚动到底部。

112971 次浏览

It needs to be done as following:

    getScrollView().post(new Runnable() {


@Override
public void run() {
getScrollView().fullScroll(ScrollView.FOCUS_DOWN);
}
});

This way the view is first updated and then scrolls to the "new" bottom.

You can do this in layout file:

                android:id="@+id/listViewContent"
android:layout_width="wrap_content"
android:layout_height="381dp"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll">

Put the following code after your data is added:

final ScrollView scrollview = ((ScrollView) findViewById(R.id.scrollview));
scrollview.post(new Runnable() {
@Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});

This works for me:

scrollview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
scrollview.post(new Runnable() {
public void run() {
scrollview.fullScroll(View.FOCUS_DOWN);
}
});
}
});

Right after you append data to the view add this single line:

yourScrollview.fullScroll(ScrollView.FOCUS_DOWN);

Try this

    final ScrollView scrollview = ((ScrollView) findViewById(R.id.scrollview));
scrollview.post(new Runnable() {
@Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});

This is the best way of doing this.

scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
});

After initializing your UI component and fill it with data. add those line to your on create method

Runnable runnable=new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
};
scrollView.post(runnable);
 scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
},1000);