淘寶首頁菜單底部的滑動位置指示器該如何實現呢?
實現方法:
1.上方橫滑列表可以直接使用RecyclerView GridLayoutManager橫向實現
2.指示器實現步驟:
(1) .計算出RecyclerView劃出屏幕的距離w1和剩餘寬度w2的比例y,y = w1 / (總寬度w3 - 可使視區域寬度w4)
(2) .計算出指示器該移動的距離w5 = y * (指示器的總寬度w6 - 滑塊寬度w7)
(3) .指示器佈局
<RelativeLayout
android:id="@+id/rl_indicator"
android:layout_width="60dp"
android:layout_height="4dp"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal"
android:background="@drawable/indicator_bg_normal">
<View
android:id="@+id/main_line"
android:layout_width="30dp"
android:layout_height="4dp"
android:layout_centerVertical="true"
android:background="@drawable/indicator_bg_select"/>
</RelativeLayout>
indicator_bg_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="5dp" />
<solid android:color="@color/gray_9" />
</shape>
indicator_bg_select.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="5dp"/>
<solid android:color="@color/red"/>
</shape>
(4) .實現代碼
rvMenu.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=0;
int temp = rvMenu.computeHorizontalScrollRange();
if (temp > range) {
range = temp;
}
//滑塊的偏移量
int offset = rvMenu.computeHorizontalScrollOffset();
//可視區域長度
int extent = rvMenu.computeHorizontalScrollExtent();
//滑出部分在剩餘範圍的比例
float proportion = (float) (offset * 1.0 / (range - extent));
//計算滾動條寬度
float transMaxRange = rlIndicator.getWidth() - mainLine.getWidth();
//設置滾動條移動
mainLine.setTranslationX(transMaxRange * proportion);
}
});