滚动到(启用垂直和水平滚动)网格布局中的特定位置 - 回收器视图 - Android



我已经用GridlayOutManager实现了一个循环浏览器,该杂志具有垂直和水平滚动,我需要将布局滚动到特定的位置,向我提及了许多代码。/p>

Java类代码:

void RackGen()
    {
        STRarray = (String[]) mStringList.toArray(new String[mStringList.size()]);
        ROWarray = (String[]) mRowList.toArray(new String[mRowList.size()]);
        numcol = Integer.parseInt(col);
        numdata = Integer.parseInt(num);
        rv = (RecyclerView) findViewById(R.id.rview);
        int numberOfColumns = numcol;
        GridLayoutManager GM2 = new GridLayoutManager(this,numberOfColumns);
        rv.setLayoutManager(GM2);

        rv.setNestedScrollingEnabled(true);
        rv.setHasFixedSize(true);
        adapter = new MyRecyclerViewAdapter(this, STRarray, ROWarray);
        rv.setAdapter(adapter);

XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="20dp"
    android:layout_centerHorizontal="true"
    android:id="@+id/llzoom"
    android:orientation="vertical"
    >
        <android.support.v4.widget.NestedScrollView
            android:id="@+id/nested_scroll_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
                <ScrollView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    xmlns:android="http://schemas.android.com/apk/res/android">
        <HorizontalScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scrollbars="none"
            android:overScrollMode="never">
        <android.support.v7.widget.RecyclerView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/rview">
        </android.support.v7.widget.RecyclerView>

        </HorizontalScrollView>
                </ScrollView>
        </android.support.v4.widget.NestedScrollView>
</LinearLayout>

仅在添加嵌套的滚动视图以及垂直和水平滚动后,滚动在两个方向上都可以顺利进行。现在我需要滚动到特定位置。

谢谢

您需要在活动中引用嵌套的crollview,然后在该对象上调用scrollTo(x,y),示例:

NestedScrollView nestedScrollView  = (NestedScrollView) findViewById(R.id.nested_scroll_view);
nestedScrollView.scrollTo(x,y);

x和y是水平和垂直卷轴。

我知道这是一个较旧的帖子,我没有在嵌套的滚动视图上测试此代码,但是由于您只有一个位置值,您可以尝试此技术。

这非常适合滚动到具有Dynamic Autofit的Recyclerview Gridlayoutmanager的当前选择的视图(我使用自定义RecyClerview用于Autofit,而不是网格本身)。

)。

设置适配器后:

recyclerView.setAdapter(adapter);

我放在(在ongreate中仅在它下方):

recyclerView.post(new Runnable()
{
    @Override
    public void run()
    {
        layoutManager.scrollToPositionWithOffset(currentSelected, 0);
    }
});

它等待绘制视图,然后滚动到给定的位置。它效果很好!

我在这里得到了想法:https://stackoverflow.com/a/52895262/2905354

最新更新