java - 如何在 horizo​​ntalScrollView 中通过平滑滚动使 View 居中

标签 java android horizontalscrollview smooth-scrolling

当元素/ View 被单击/制表时,我试图在 horizo​​ntalScrollView 中通过平滑滚动使 View 居中。

这是我为实现这一目标所做的最新尝试。

代码:

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

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

我觉得没有必要包含所有代码,但 DrinkCategoryView 是 horizo​​ntalScrollView 的项目 View 所在的类。 名为 barsScroller 的变量是 horizo​​ntalScrollView。

这是包含 View 的 horizo​​ntalScrollView 和 linearlayout 的 xml 部分:

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

我希望你能理解我正在努力实现的目标,也许能帮助我朝着正确的方向前进。

任何帮助将不胜感激。

最佳答案

尝试这样的事情:

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

如果这仍然无效,您可能想以图像的形式发布失败的测试结果。

关于java - 如何在 horizo​​ntalScrollView 中通过平滑滚动使 View 居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32382902/

相关文章:

java - 为什么 Java 的行为不像 "Pass-By-Value"一样?

android - Skype Android 应用程序是如何做到的?

java - 如何解决向 Firebase 数据库添加数据的问题

安卓 : gradlew lint error "Incompatible Gradle Versions"

android - 内容拉伸(stretch)以填充 Horizo​​ntalScrollView

android - 将水平 ScrollView 添加到 ListView

java - 在Android中使用Ksoap2调用不同命名空间的WSDL

java - TreeMap 元素未删除

java - 解码由php保存的未知字符集文本

android - 如何水平滚动 LinearLayout?