HorizontalScrollView: auto-scroll to end when new Views are added?

后端 未结 9 1199
鱼传尺愫
鱼传尺愫 2020-11-28 06:37

I have a HorizontalScrollView containing a LinearLayout. On screen I have a Button that will add new Views to the LinearLayout at runtime, and I\'d like the scroll view to

9条回答
  •  没有蜡笔的小新
    2020-11-28 07:20

    I think there's a timing issue. Layout isn't done when a view is added. It is requested and done a short time later. When you call fullScroll immediately after adding the view, the width of the linearlayout hasn't had a chance to expand.

    Try replacing:

    s.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
    

    with:

    s.postDelayed(new Runnable() {
        public void run() {
            s.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
        }
    }, 100L);
    

    The short delay should give the system enough time to settle.

    P.S. It might be sufficient to simply delay the scrolling until after the current iteration of the UI loop. I have not tested this theory, but if it's right, it would be sufficient to do the following:

    s.post(new Runnable() {
        public void run() {
            s.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
        }
    });
    

    I like this better because introducing an arbitrary delay seems hacky to me (even though it was my suggestion).

提交回复
热议问题