recyclerview滑动条
时间: 2023-09-18 11:13:56 浏览: 45
你可以在布局文件中添加一个 `RecyclerView` 和一个 `ScrollBar` 组件。然后使用 `RecyclerView` 的 `scrollToPosition()` 方法来实现滑动功能。
以下是一个示例布局文件:
```xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<ScrollBar
android:id="@+id/scroll_bar"
android:layout_width="20dp"
android:layout_height="match_parent"/>
</LinearLayout>
```
然后在你的代码中设置 `ScrollBar` 的最大值为 `RecyclerView` 的 item 数量,然后在 `RecyclerView` 的滑动事件中更新 `ScrollBar` 的进度。
```java
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
ScrollBar scrollBar = (ScrollBar) findViewById(R.id.scroll_bar);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int itemCount = recyclerView.getLayoutManager().getItemCount();
int visibleItemCount = recyclerView.getLayoutManager().getChildCount();
int firstVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
int scrollRange = itemCount - visibleItemCount;
if (scrollRange > 0) {
int scrollProgress = (int) (100.0 * firstVisibleItemPosition / scrollRange);
scrollBar.setProgress(scrollProgress);
} else {
scrollBar.setProgress(0);
}
}
});
```
这样就可以实现一个带滑动条的 `RecyclerView` 了。