Android之RecyclerView自定義滾動條

根據需求針對橫向顯示的列表增加一個滾動條顯示。

效果圖:

Recycleview列表實現原來是啥就是啥,先看看列表下面的滾動條。

滾動條佈局:

               <FrameLayout
                    android:id="@+id/lay_slip"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:visibility="invisible">

                    <View
                        android:layout_width="60dp"
                        android:layout_height="5dp"
                        android:background="@drawable/shape_bg_slip_behind" />

                    <View
                        android:id="@+id/view_slip_front"
                        android:layout_width="40dp"
                        android:layout_height="4dp"
                        android:layout_gravity="center_vertical"
                        android:layout_marginLeft="1dp"
                        android:layout_marginRight="1dp"
                        android:background="@drawable/shape_bg_slip_front" />
                </FrameLayout>

資源文件shape_bg_slip_behind.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/gray" />
    <corners android:radius="2dp" />
</shape>

資源文件shape_bg_slip_front.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/login_btn_right" />
    <corners android:radius="2dp" />
</shape>

 之後就需要監聽列表的滑動事件了。

        // 這裏的mRvHx是需要綁定滾動條的RecyclerView
        rv_main_app.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @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 range = rv_main_app.computeHorizontalScrollRange();
                float density = getScreenDensity();
                // 計算出溢出部分的寬度,即屏幕外剩下的寬度
                float maxEndX = range - ScreenUtils.getScreenWidth() + (25 * density) + 5;
                // 滑動的距離
                endX[0] = endX[0] + dx;
                // 計算比例
                float proportion = endX[0] / maxEndX;

                // 計算滾動條寬度
                int transMaxRange = ((ViewGroup) view_slip_front.getParent()).getWidth() - view_slip_front.getWidth();
                // 設置滾動條移動
                view_slip_front.setTranslationX(transMaxRange * proportion);
            }

        });

注意:當數據刷新時需要改變爲初始的樣子:

view_slip_front.setTranslationX(0);
rv_view.scrollToPosition(0);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章