开发者

Horizontalscrollview initial offset value

How to set HorizontalScrollView's initial 开发者_如何学编程offset value? I used smoothScrolTo() but it is not working.

Please help.


Use View.getViewTreeObserver.addOnGlobalLayoutListener to add listener for knowing when scrollview is laid. In the callback you can set scroll.

Use removeGlobalOnLayoutListener(this) in the callback to unregister for further events.

scroll.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
   @Override
   public void onGlobalLayout(){
      scroll.getViewTreeObserver().removeGlobalOnLayoutListener(this);
      scroll.scrollTo(x, y);
   }
});


You can not call smoothScrolTo() during onCreate, onStart or onResume. try to give a small delay like this:

public void onResume() {
    super.onResume();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            HorizontalScrollView sv = (HorizontalScrollView)findViewById(R.id.ScrollView01);
            sv.smoothScrollTo(1000, 0);
        }
    }, 100);
}

This works for me, but dose anyone know a better time(e.g. in a listener) for calling smoothScrollTo?


Another way to solve this is via xml.

The trick is add "Spaces views" as childs of the HorizontalScrollView and set the width of them to the offset you want to have.

Example:

<!--BUTTONS ON HORIZONAL SCROLL -->
    <HorizontalScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/scroll_view_child_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <!-- This View does the trick! -->
            <Space
                android:layout_width="16dp"
                android:layout_height="match_parent" />

            <Button
                android:id="@+id/btn_1"
                style="@style/HorizontalScrollButtons"
                android:text="Btn1" />

            <Button
                android:id="@+id/btn_2"
                style="@style/HorizontalScrollButtons"
                android:text="Btn1" />

            <!-- Keep adding buttons... -->

            <!-- This View does the trick too! -->
            <Space
                android:layout_width="16dp"
                android:layout_height="match_parent" />


        </LinearLayout>

    </HorizontalScrollView>

In the example I want a 16dp "margin" so I give the Space View a width of 16dp.

It will give this...

Horizontalscrollview initial offset value

...instead of this...

Horizontalscrollview initial offset value

...as starting view.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜