提问者:小点点

有没有办法在代码中为回收器视图启用滚动条?


正如我们所看到的,RecyclerView比ListView更有效,所以我更喜欢在我的项目中使用它。但是最近,当将其放入自定义视图组中时,我遇到了麻烦。RecyclerView很容易在xml中设置滚动条,如下所示:

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

但是我真的找不到任何方法来为RecyclerView的代码设置滚动条,我尝试的是:

mRecyclerView.setVerticalScrollBarEnabled(true);

然后我在Android的文档中看到了这个。

所以我尝试制作自己的布局管理器并覆盖我认为我需要的功能。但最后我失败了。所以谁能告诉我应该如何制作自己的布局管理器或只是向我展示其他解决方案。谢谢!


共3个答案

匿名用户

目前,似乎无法以编程方式启用滚动条。这种行为的原因是Android没有调用View.initializeScrollbarsInternal(TypedArray a)或View.initializeScrollbars(TypedArray a)。仅当您使用 AttributeSet 实例化 RecyclerView 时,才会调用这两种方法。
作为解决方法,我建议您仅使用RecyclerView创建一个新的布局文件:vertical_recycler_view.xml

<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />

现在,您可以充气并添加带有滚动条的RecyclerView:MyCustomViewGroup.java

public class MyCustomViewGroup extends FrameLayout
{
    public MyCustomViewGroup(Context context)
    {
        super(context);

        RecyclerView verticalRecyclerView = (RecyclerView) LayoutInflater.from(context).inflate(R.layout.vertical_recycler_view, null);
        verticalRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        addView(verticalRecyclerView);
    }
}

匿名用户

在 xml 布局中设置垂直滚动条

<android.support.v7.widget.RecyclerView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:scrollbars="vertical" />

匿名用户

仅在 xml 属性中

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/recyclerView"
    android:scrollbars="vertical" <!-- type of scrollbar -->
    android:scrollbarThumbVertical="@android:color/darker_gray"  <!--color of scroll bar-->
    android:scrollbarSize="5dp"> <!--width of scroll bar-->

</android.support.v7.widget.RecyclerView>