2015-09-03 176 views
1

我試圖用horizo​​ntalScrollView中的平滑滾動居中,單擊/選中元素/視圖。如何在水平滾動視圖中使用平滑滾動居中視圖

這是我最近嘗試實現的目標。

代碼:

public void scrollCenterBarItem(DrinkCategoryView toBarItem) { 
    int endPos = (int) toBarItem.getView().getX(); 
    int halfWidth = (int) toBarItem.getView().getWidth()/2; 

    barsScroller.smoothScrollTo(endPos + halfWidth, 0); 
} 

我並不覺得neccesary包括所有的代碼,但DrinkCategoryView是在horizo​​ntalScrollView的項目視圖位於一類。 稱爲barsScroller的變量是horizo​​ntalScrollView。

這裏是XML的一部分,其中horizo​​ntalScrollView和LinearLayout中,包含的意見是:

 <HorizontalScrollView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/bars_scroller" 
      android:layout_alignParentTop="true" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentStart="true" 
      android:layout_alignParentRight="true" 
      android:layout_alignParentEnd="true" 
      android:scrollbars="none"> 
      <LinearLayout 
       android:id="@+id/drinksCategoryList" 
       android:orientation="horizontal" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" /> 
     </HorizontalScrollView> 
    </RelativeLayout> 

這裏是Horizo​​ntalScrollView的項目XML佈局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:orientation="vertical" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/drinkCategoryItem"> 


    <com.ivankocijan.magicviews.views.MagicTextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/drinkCategoryItemTextView" 
     android:textSize="18sp" 
     app:typeFace="@string/opensans_regular" 
     android:textColor="@color/black" 
     android:padding="16dp" /> 
</LinearLayout> 

我希望你能理解我想要達到的目標,也許能幫助我走向正確的方向。

任何幫助將不勝感激。

回答

4

嘗試這樣:

public void scrollCenterBarItem(DrinkCategoryView toBarItem) { 
    int endPos = (int) toBarItem.getView().getX(); 
    int halfWidth = (int) toBarItem.getView().getWidth()/2; 

    barsScroller.smoothScrollTo(endPos + halfWidth - barScroller.getWidth()/2, 0); 
} 

如果仍然沒有工作,你可能想發表您失敗的測試結果在圖像的形式。

+0

哇,非常感謝,它完美的作品:D接受和+1 – Langkiller