本人蔘考了http://www.cnblogs.com/chaoxiyouda/p/5265936.html的文章,並在其基礎上稍作更改,增加了部分註釋
效果圖
關鍵代碼: mainActivity中 slidingTabLayout.setTabTitleTextSize(14);//標題字體大小 slidingTabLayout.setTitleTextColor(Color.BLACK, Color.RED);//標題字體顏色 slidingTabLayout.setTabStripWidth(40);//滑動條寬度 slidingTabLayout.setSelectedIndicatorColors(Color.RED,Color.BLACK,Color.YELLOW);//滑動條顏色 slidingTabLayout.setDistributeEvenly(false); //均勻平鋪選項卡 slidingTabLayout.setViewPager(viewPager);//最後調用此方法 SlidingTabStrip自定義控件中: 源代碼 canvas.drawRect(left + cutWidth, height - mSelectedIndicatorThickness, right - cutWidth, height, mSelectedIndicatorPaint); 更改後代碼,想設計什麼長度自己去拓展 mSelectionOffset是滾動比例 if(mSelectionOffset<=0.5){ Log.w("輸出0.5以下",right - cutWidth+mSelectionOffset*tabWidth+""); canvas.drawRect(left + cutWidth, height - mSelectedIndicatorThickness, right - cutWidth+mSelectionOffset*tabWidth, height, mSelectedIndicatorPaint); }else { Log.w("輸出0.5以上",right - cutWidth+(mSelectionOffset-0.50)*tabWidth+""); canvas.drawRect(left + cutWidth, height - mSelectedIndicatorThickness, (float) (right - cutWidth+(1-mSelectionOffset)*tabWidth), height, mSelectedIndicatorPaint); }
注意:在Android5.0之後如果需要去掉分隔線,去掉懸浮狀態,套上AppBarLayout並設置app:elevation="0dp"
<android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:elevation="0dp">
<org.xufei.sliding_tab.SlidingTabLayout android:id="@+id/sliding_tabs" android:layout_width="match_parent" android:layout_height="wrap_content" android:translationZ="3dp" android:background="#ffffff"/></android.support.design.widget.AppBarLayout>
DEMO下載地址:http://download.csdn.net/detail/kac930/9787606