您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“Android仿天貓橫向滑動(dòng)指示器功能如何實(shí)現(xiàn)”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
Android開發(fā)中會(huì)有很多很新奇的交互,比如天貓商城的首頁頭部的分類,使用的是GridLayoutManager+橫向指示器實(shí)現(xiàn)的,效果如下圖。
那對(duì)于這種效果要如何實(shí)現(xiàn)呢?最簡(jiǎn)單的方式就是使用RecyclerView+GridLayoutManager,我們知道RecyclerView可以實(shí)現(xiàn)九宮格,接下來就是通過RecyclerView控制指示器的顯示位置,邏輯實(shí)現(xiàn)如下:
計(jì)算出RecyclerView劃出屏幕的距離w1和剩余寬度w2的比例y,y = w1 / (總寬度w3 - 可使視區(qū)域?qū)挾葁4)
計(jì)算出指示器該移動(dòng)的距離w5 = y * (指示器的總寬度w6 - 滑塊寬度w7)
指示器布局,并控制位置
首先,我們創(chuàng)建兩個(gè)drawable文件,分別用于表示指示器的默認(rèn)背景和選中的背景。
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>
然后,我們?cè)偬砑右粋€(gè)布局,上面是RecyclerView,下面是指示器。
<androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="0dp" android:layout_height="@dimen/dp_120" android:layout_marginBottom="@dimen/dp_10"/> <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>
接下來,就是通過監(jiān)聽RecyclerView的橫向滾動(dòng)的距離,來判斷指示器顯示的位置,代碼如下。
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(); //可視區(qū)域長(zhǎng)度 int extent = rvMenu.computeHorizontalScrollExtent(); //滑出部分在剩余范圍的比例 float proportion = (float) (offset * 1.0 / (range - extent)); //計(jì)算滾動(dòng)條寬度 float transMaxRange = rlIndicator.getWidth() - mainLine.getWidth(); //設(shè)置滾動(dòng)條移動(dòng) mainLine.setTranslationX(transMaxRange * proportion); } });
“Android仿天貓橫向滑動(dòng)指示器功能如何實(shí)現(xiàn)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。