老早之前做的一个功能,横向recyclerview滑动时,底部做跟随滑动指示器。今天代码不用了,记录下代码。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/fourteen"
android:orientation="vertical"
android:paddingLeft="@dimen/sixteen"
android:paddingRight="@dimen/sixteen">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_teacher"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.recyclerview.widget.RecyclerView>
<RelativeLayout
android:id="@+id/scroll_bar_bg"
android:layout_width="30dp"
android:layout_height="4dp"
android:layout_gravity="center"
android:layout_marginTop="@dimen/six"
android:background="@drawable/bg_fast_view">
<View
android:id="@+id/scroll_bar"
android:layout_width="20dp"
android:layout_height="4dp"
android:layout_centerVertical="true"
android:background="@drawable/bg_scroll_bar" />
</RelativeLayout>
</LinearLayout>
bg_fast_view
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="@color/Gray"/>
<corners
android:radius="@dimen/ten"/>
</shape>
bg_scroll_bar
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="@color/title_bg"/>
<corners
android:radius="@dimen/ten"/>
</shape>
RelativeLayout scrollBarBg = view.findViewById(R.id.parent_layout);
View scrollBar = view.findViewById(R.id.main_line);
GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
rvTeacher.setLayoutManager(layoutManager);
teacherAdapter = new RecommendTeacherRVAdapter(mContext);
rvTeacher.setAdapter(teacherAdapter);
rvTeacher.addOnScrollListener(new RecyclerView.OnScrollListener() {
public int range = 0;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
//整体的总宽度,注意是整体,包括在显示区域之外的。
int temp = recyclerView.computeHorizontalScrollRange();
if (temp > range) {
range = temp;
}
int offset = recyclerView.computeHorizontalScrollOffset();
int extent = recyclerView.computeHorizontalScrollExtent();
float proportion = (float) (offset * 1.0 / (range - extent));
//计算滚动条宽度
float transMaxRange = scrollBarBg.getWidth() - scrollBar.getWidth();
//设置滚动条移动
scrollBar.setTranslationX(transMaxRange * proportion);
}
});