ScrollView を一番下から開始したいと思います。方法はありますか?
19 に答える
次のようにscroll.post内でコードを実行する必要があります。
scroll.post(new Runnable() {
@Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
scroll.fullScroll(View.FOCUS_DOWN)
も動作するはずです。
これをscroll.Post(Runnable run)
Kotlin コード
scrollView.post {
scrollView.fullScroll(View.FOCUS_DOWN)
}
scroll.fullScroll(View.FOCUS_DOWN)
意識の変化につながります。これにより、フォーカス可能なビューが複数ある場合、たとえば 2 つの EditText など、奇妙な動作が発生します。この質問には別の方法があります。
View lastChild = scrollLayout.getChildAt(scrollLayout.getChildCount() - 1);
int bottom = lastChild.getBottom() + scrollLayout.getPaddingBottom();
int sy = scrollLayout.getScrollY();
int sh = scrollLayout.getHeight();
int delta = bottom - (sy + sh);
scrollLayout.smoothScrollBy(0, delta);
これはうまくいきます。
Kotlin 拡張機能
fun ScrollView.scrollToBottom() {
val lastChild = getChildAt(childCount - 1)
val bottom = lastChild.bottom + paddingBottom
val delta = bottom - (scrollY+ height)
smoothScrollBy(0, delta)
}
私にとって最もうまくいったのは
scroll_view.post(new Runnable() {
@Override
public void run() {
// This method works but animates the scrolling
// which looks weird on first load
// scroll_view.fullScroll(View.FOCUS_DOWN);
// This method works even better because there are no animations.
scroll_view.scrollTo(0, scroll_view.getBottom());
}
});
考慮すべきことの 1 つは、何を設定しないかということです。子コントロール、特に EditText コントロールに RequestFocus プロパティが設定されていないことを確認してください。これは、レイアウトで最後に解釈されたプロパティの 1 つである可能性があり、その親 (レイアウトまたは ScrollView) の重力設定をオーバーライドします。
ビューがまだ読み込まれていない場合は、スクロールできません。上記のように post または sleep コールを使用して「後で」実行できますが、これはあまりエレガントではありません。
スクロールを計画して、次の onLayout() で実行することをお勧めします。ここにコード例:
これは即座に機能します。遅滞なく。
// wait for the scroll view to be laid out
scrollView.post(new Runnable() {
public void run() {
// then wait for the child of the scroll view (normally a LinearLayout) to be laid out
scrollView.getChildAt(0).post(new Runnable() {
public void run() {
// finally scroll without animation
scrollView.scrollTo(0, scrollView.getBottom());
}
}
}
}
scroll.fullScroll(View.FOCUS_DOWN)
ラップしても機能しない可能性がある理由の 1 つ.post()
は、ビューがレイアウトされていないことです。この場合、View.doOnLayout()がより良いオプションになる可能性があります:
scroll.doOnLayout(){
scroll.fullScroll(View.FOCUS_DOWN)
}
または、勇敢な魂のためにもっと精巧な何か: https://chris.banes.dev/2019/12/03/suspending-views/
最小 SDK が 23 以上の場合、これを使用できます。
View childView = findViewById(R.id.your_view_id_in_the_scroll_view)
if(childView != null){
scrollview.post(() -> scrollview.scrollToDescendant(childView));
}