2011-03-01 99 views

回答

3

在onCreate,onStart或onResume期间,您无法调用smoothScrolTo()。试着给一个小的延迟是这样的:

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); 
} 

这对我的作品,但剂量任何人都知道一个更好的时间调用smoothScrollTo(如在听众。)?

10

使用View.getViewTreeObserver.addOnGlobalLayoutListener添加监听器以了解何时放置滚动视图。在回调中,您可以设置滚动。

在回调中使用removeGlobalOnLayoutListener(this)取消注册其他事件。

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

解决此问题的另一种方法是通过xml。

的诀窍是添加“空间意见”Horizo​​ntalScrollView的孩子的,并将它们的宽度设置为偏移您想拥有。

实施例:

<!--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> 

在我想要一个16DP “余量” 的例子,所以我得到空间查看16DP的宽度

它会给这个... The way we want

...而不是这个...... enter image description here

...为起始视图。

相关问题