74

Background

On ListView, you could have a fast scroller which allowed you to drag a scrollbar to easily scroll to wherever you wished (using fastScrollEnabled attribute)

Together with "SectionIndexer" class and optionally some attributes, you could have a nice popup that shows as you use this scrollbar (link here).

Such a thing is shown on the contacts app so that you could scroll easily to specific letters.

The problem

RecyclerView doesn't seem to have any of those. Not even a fast-scroll.

The question

How do I add a fast scroller functionality for the RecyclerView?

4

11 回答 11

52

几天前,当我遇到这种情况时,我偶然发现了这个问题。这是我为 RecyclerView 实现 FastScroll 的示例

github.com/danoz73/RecyclerViewFastScroller

尝试运行示例应用程序,并仔细阅读代码以查看简单 RecyclerViewFastScroller 小部件的相当简单的用法。github 上有相关信息,但我将在此处介绍垂直快速滚动条的基本用法。

有关完整示例,请参阅repo 中的示例应用程序

基本用法

在 RecyclerView 所在的活动或片段 XML 中,包含一个 VerticalRecyclerViewFastScroller 对象。以下示例将采用相对布局:

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


  <xyz.danoz.recyclerviewfastscroller.vertical.VerticalRecyclerViewFastScroller
      android:id="@+id/fast_scroller"
      android:layout_width="@dimen/however_wide_you_want_this"
      android:layout_height="match_parent"
      android:layout_alignParentRight="true"
    />
...

在以编程方式设置布局的片段或活动中,将快速滚动条连接到回收器:

...
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      View rootView = inflater.inflate(R.layout.recycler_view_frag, container, false);
      ...

      // Grab your RecyclerView and the RecyclerViewFastScroller from the layout
      RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
      VerticalRecyclerViewFastScroller fastScroller = (VerticalRecyclerViewFastScroller) rootView.findViewById(R.id.fast_scroller);

      // Connect the recycler to the scroller (to let the scroller scroll the list)
      fastScroller.setRecyclerView(recyclerView);

      // Connect the scroller to the recycler (to let the recycler scroll the scroller's handle)
      recyclerView.setOnScrollListener(fastScroller.getOnScrollListener());

      ...
      return rootView;
  }
...

希望这可以帮助!

编辑:现在添加了对 Android-Lollipop-Contacts 样式部分指示器的支持!查看示例应用程序的实现以了解详细信息。

于 2015-02-13T07:07:33.297 回答
29

新答案:随着时间的推移,我注意到我的原始答案与其他解决方案相比存在一些缺点,尤其是对于 ViewPager 中的片段。

如果你不需要气泡,我建议要么使用android-x 解决方案,要么使用第三方库(是一个很好的),以防你这样做。


旧答案:

由于所有第三方库都有问题,我决定收集我能找到的东西(主要来自这里),修复所有内容并发布我自己的 RecyclerView 快速滚动器的 POC:

https://github.com/AndroidDeveloperLB/LollipopContactsRecyclerViewFastScroller

用法:

  1. 制作一个实现 BubbleTextGetter 的 RecyclerView.Adapter,给定数据中的位置将返回要在气泡弹出窗口中显示的文本。

  2. 将 FastScroller 放置在包含 RecyclerView 的布局内(可能在右侧区域)。

  3. 自定义 FastScroller FastScroller

一些缺点:

  1. 不支持方向更改,但可能很容易修复。
  2. 不支持其他布局管理器。只有线性布局管理器
  3. 需要 API 11 及更高版本。

代码:

BubbleTextGetter

public interface BubbleTextGetter
  {
  String getTextToShowInBubble(int pos);
  }

recycler_view_fast_scroller__fast_scroller.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="wrap_content"
       android:layout_height="match_parent">

  <TextView
    android:id="@+id/fastscroller_bubble"
    android:layout_gravity="right|end"
    android:gravity="center"
    android:textSize="48sp" tools:text="A"
    android:layout_width="wrap_content"
    android:textColor="#FFffffff"
    android:layout_height="wrap_content"
    android:background="@drawable/recycler_view_fast_scroller__bubble"
    android:visibility="visible"/>

  <ImageView
    android:id="@+id/fastscroller_handle"
    android:layout_width="wrap_content"
    android:layout_marginRight="8dp"
    android:layout_marginLeft="8dp"
    android:layout_height="wrap_content"
    android:src="@drawable/recycler_view_fast_scroller__handle"/>

</merge>

主要活动

...
fastScroller=(FastScroller)findViewById(R.id.fastscroller);
fastScroller.setRecyclerView(recyclerView);

快速滚动器

public class FastScroller extends LinearLayout
  {
  private static final int BUBBLE_ANIMATION_DURATION=100;
  private static final int TRACK_SNAP_RANGE=5;

  private TextView bubble;
  private View handle;
  private RecyclerView recyclerView;
  private final ScrollListener scrollListener=new ScrollListener();
  private int height;

  private ObjectAnimator currentAnimator=null;

  public FastScroller(final Context context,final AttributeSet attrs,final int defStyleAttr)
    {
    super(context,attrs,defStyleAttr);
    initialise(context);
    }

  public FastScroller(final Context context)
    {
    super(context);
    initialise(context);
    }

  public FastScroller(final Context context,final AttributeSet attrs)
    {
    super(context,attrs);
    initialise(context);
    }

  private void initialise(Context context)
    {
    setOrientation(HORIZONTAL);
    setClipChildren(false);
    LayoutInflater inflater=LayoutInflater.from(context);
    inflater.inflate(R.layout.recycler_view_fast_scroller__fast_scroller,this,true);
    bubble=(TextView)findViewById(R.id.fastscroller_bubble);
    handle=findViewById(R.id.fastscroller_handle);
    bubble.setVisibility(INVISIBLE);
    }

  @Override
  protected void onSizeChanged(int w,int h,int oldw,int oldh)
    {
    super.onSizeChanged(w,h,oldw,oldh);
    height=h;
    }

  @Override
  public boolean onTouchEvent(@NonNull MotionEvent event)
    {
    final int action=event.getAction();
    switch(action)
      {
      case MotionEvent.ACTION_DOWN:
        if(event.getX()<handle.getX())
          return false;
        if(currentAnimator!=null)
          currentAnimator.cancel();
        if(bubble.getVisibility()==INVISIBLE)
          showBubble();
        handle.setSelected(true);
      case MotionEvent.ACTION_MOVE:
        setPosition(event.getY());
        setRecyclerViewPosition(event.getY());
        return true;
      case MotionEvent.ACTION_UP:
      case MotionEvent.ACTION_CANCEL:
        handle.setSelected(false);
        hideBubble();
        return true;
      }
    return super.onTouchEvent(event);
    }

  public void setRecyclerView(RecyclerView recyclerView)
    {
    this.recyclerView=recyclerView;
    recyclerView.setOnScrollListener(scrollListener);
    }

  private void setRecyclerViewPosition(float y)
    {
    if(recyclerView!=null)
      {
      int itemCount=recyclerView.getAdapter().getItemCount();
      float proportion;
      if(handle.getY()==0)
        proportion=0f;
      else if(handle.getY()+handle.getHeight()>=height-TRACK_SNAP_RANGE)
        proportion=1f;
      else
        proportion=y/(float)height;
      int targetPos=getValueInRange(0,itemCount-1,(int)(proportion*(float)itemCount));
      recyclerView.scrollToPosition(targetPos);
      String bubbleText=((BubbleTextGetter)recyclerView.getAdapter()).getTextToShowInBubble(targetPos);
      bubble.setText(bubbleText);
      }
    }

  private int getValueInRange(int min,int max,int value)
    {
    int minimum=Math.max(min,value);
    return Math.min(minimum,max);
    }

  private void setPosition(float y)
    {
    int bubbleHeight=bubble.getHeight();
    int handleHeight=handle.getHeight();
    handle.setY(getValueInRange(0,height-handleHeight,(int)(y-handleHeight/2)));
    bubble.setY(getValueInRange(0,height-bubbleHeight-handleHeight/2,(int)(y-bubbleHeight)));
    }

  private void showBubble()
    {
    AnimatorSet animatorSet=new AnimatorSet();
    bubble.setVisibility(VISIBLE);
    if(currentAnimator!=null)
      currentAnimator.cancel();
    currentAnimator=ObjectAnimator.ofFloat(bubble,"alpha",0f,1f).setDuration(BUBBLE_ANIMATION_DURATION);
    currentAnimator.start();
    }

  private void hideBubble()
    {
    if(currentAnimator!=null)
      currentAnimator.cancel();
    currentAnimator=ObjectAnimator.ofFloat(bubble,"alpha",1f,0f).setDuration(BUBBLE_ANIMATION_DURATION);
    currentAnimator.addListener(new AnimatorListenerAdapter()
    {
    @Override
    public void onAnimationEnd(Animator animation)
      {
      super.onAnimationEnd(animation);
      bubble.setVisibility(INVISIBLE);
      currentAnimator=null;
      }

    @Override
    public void onAnimationCancel(Animator animation)
      {
      super.onAnimationCancel(animation);
      bubble.setVisibility(INVISIBLE);
      currentAnimator=null;
      }
    });
    currentAnimator.start();
    }

  private class ScrollListener extends OnScrollListener
    {
    @Override
    public void onScrolled(RecyclerView rv,int dx,int dy)
      {
      View firstVisibleView=recyclerView.getChildAt(0);
      int firstVisiblePosition=recyclerView.getChildPosition(firstVisibleView);
      int visibleRange=recyclerView.getChildCount();
      int lastVisiblePosition=firstVisiblePosition+visibleRange;
      int itemCount=recyclerView.getAdapter().getItemCount();
      int position;
      if(firstVisiblePosition==0)
        position=0;
      else if(lastVisiblePosition==itemCount-1)
        position=itemCount-1;
      else
        position=firstVisiblePosition;
      float proportion=(float)position/(float)itemCount;
      setPosition(height*proportion);
      }
    }
  }
于 2015-04-04T21:36:32.883 回答
12

Android 支持库 26.0.0 现在支持fastScrollEnabled

RecyclerView 的新 fastScrollEnabled 布尔标志。

如果启用,则必须设置 fastScrollHorizo​​ntalThumbDrawable、fastScrollHorizo​​ntalTrackDrawable、fastScrollVerticalThumbDrawable 和 fastScrollVerticalTrackDrawable。

示例 - https://android.jlelse.eu/fast-scrolling-with-recyclerview-2b89d4574688

于 2017-07-25T11:47:54.993 回答
11

关于快速滚动/部分索引器有很多未解决的问题RecyclerView我们在这里尝试重新组合并收集我们的意见和信息。

简短的回答是: 不,您不能启用快速滚动,因为RecyclerView不包含FastScroller对象,也不包含任何相关的逻辑状态变量。这是因为RecyclerView不是AbsListView

另一方面,实现RecyclerView包含FastScroller快速滚动的转储版本和必要逻辑的 a 并非不可能,但到目前为止我还没有看到任何实现。

请分享您对此的考虑,或者如果您认为我错了。

于 2015-01-18T19:01:42.207 回答
4

您也可以将 AZ Fastscroll 用于 RecyclerView。这是iOS风格。

https://github.com/code-computerlove/FastScrollRecyclerView/

如何使用它:

  • 替换android.support.v7.widget.RecyclerViewcom.codecomputerlove.fastscrollrecyclerviewdemo.FastScrollRecyclerView
  • 您的适配器需要实现 FastScrollRecyclerViewInterface 和 override getMapIndex()。该函数应返回 mapIndex。寻找calculateIndexesForName()有关如何创建它的灵感。创建后将其传递给构造函数中的适配器。
  • 创建一个实例FastScrollRecyclerViewItemDecoration并将其添加到您的 RecyclerView FastScrollRecyclerViewItemDecoration decoration = new FastScrollRecyclerViewItemDecoration(this); mRecyclerView.addItemDecoration(decoration);
  • 添加<dimen name="fast_scroll_overlay_text_size">100dp</dimen>到您的 /values/dimens.xml文件中。这是覆盖字母的 dp 大小
于 2015-03-06T12:45:09.323 回答
4

FastScroller 功能是从 android 库 26.0.0 中为RecyclerView添加的

编译依赖

    compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.android.support:design:26.1.0'

添加对 project.gradle 的依赖

     maven {
            url "https://maven.google.com"
        }

你的 recyclerview.xml 文件

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    xmlns:tool="http://schemas.android.com/tools"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    tool:context=".MainActivity">
    <android.support.v7.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:id="@+id/songlist"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                app:fastScrollEnabled="true"
              app:fastScrollVerticalThumbDrawable="@drawable/thumb_drawable"
                app:fastScrollVerticalTrackDrawable="@drawable/line_drawable"
                app:fastScrollHorizontalThumbDrawable="@drawable/thumb_drawable"
                app:fastScrollHorizontalTrackDrawable="@drawable/line_drawable"
               /></LinearLayout>

拇指.xml

   <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">

    <corners
        android:topLeftRadius="44dp"
        android:topRightRadius="44dp"
        android:bottomLeftRadius="44dp"
        android:bottomRightRadius="44dp" />

    <padding
        android:paddingLeft="22dp"
        android:paddingRight="22dp" />

    <solid android:color="#f73831" />

</shape>

行.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">

    <solid android:color="@color/dark_grey" />

    <padding
        android:top="10dp"
        android:left="10dp"
        android:right="10dp"
        android:bottom="10dp"/>
</shape>

thumb_drawable.xml

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/thumb"
        android:state_focused="true"
        android:state_pressed="true" />

    <item android:drawable="@drawable/thumb"
        android:state_focused="false"
        android:state_pressed="true" />
    <item android:drawable="@drawable/thumb" 
            android:state_focused="true" />
    <item android:drawable="@drawable/thumb"
        android:state_focused="false"
        android:state_pressed="false" />
</selector>

line_drawble.xml

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/line"
        android:state_focused="true"
        android:state_pressed="true" />

    <item android:drawable="@drawable/line"
        android:state_focused="false"
        android:state_pressed="true" />
    <item android:drawable="@drawable/line" 
            android:state_focused="true" />
    <item android:drawable="@drawable/line"
        android:state_focused="false"
        android:state_pressed="false" />
</selector>
于 2018-02-21T12:16:55.617 回答
3

你可以试试我们的库:https ://github.com/FutureMind/recycler-fast-scroll 。它仍处于早期开发阶段,但专门用于处理我们在其他库中遇到的平滑问题。它使用了一些不同的机制。它也支持水平布局管理器,并且在不久的将来还将支持多列设置。

编辑:现在有一些简洁的自定义选项。

于 2015-12-04T19:21:31.763 回答
1

RecycleView提供了使用及其实现滚动条的规定LayoutManager

例如:computeVerticalScrollExtent()computeVerticalScrollOffset()可以computeVerticalScrollRange()提供始终将垂直滚动拇指定位在正确位置的信息。

这些方法也LayoutManager用于委派实际测量。所以LayoutManager使用的实现必须支持这些测量。

此外,可以通过覆盖来拦截滚动拇指上的拖动onInterceptTouchEvent()触摸RecyclerView。并在计算出所需的滚动后,scrollTo()可以调用 update RecyclerView

于 2015-02-12T19:04:51.750 回答
1

这个新库基于框架启动器的快速滚动器:https ://github.com/zhanghai/AndroidFastScroll

用法

new FastScrollerBuilder(recyclerView).build();

可选地PopupTextProvider在适配器中实现。

于 2019-12-10T11:19:01.163 回答
0

android studio中的fast-scroller仍然有很多bug,因为它只基于xml,所以我去挖掘可以实现快速滚动的外部库。你可以在 这里得到它。非常容易实施和定制。

于 2020-07-20T06:58:21.443 回答
0

只需启用快速滚动并添加拇指,滚动条的跟踪器,如下所示。

<android.support.v7.widget.RecyclerView
android:id="@+id/rv_sensors"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:fastScrollEnabled="true"
app:fastScrollHorizontalThumbDrawable="@drawable/thumb_drawable"
app:fastScrollHorizontalTrackDrawable="@drawable/line_drawable"
app:fastScrollVerticalThumbDrawable="@drawable/thumb_drawable"
app:fastScrollVerticalTrackDrawable="@drawable/line_drawable" />
于 2018-08-07T07:19:21.690 回答