1. 程式人生 > >TabLayout自定義選擇背景滑塊

TabLayout自定義選擇背景滑塊

TabLayout是Android 的Material Design包中的一個控制元件,可以和V4包中的ViewPager搭配產生一個聯動的效果。這裡我自定義了一個滑塊能夠跟隨TabLayout進行滑動選擇的SliderLayout。效果見下圖(白色方框):
SliderLayout效果
下面是MTabLayout的原始碼(之前的程式碼有一些bug,當TabLayout本身進行滑動的時候會和Slider錯開,所以就自定義了一個MTabLayout,並把SliderLayout作為內部類放到MTabLayout):

import android.content.Context;
import android.graphics.drawable.Drawable;
import
android.support.annotation.DrawableRes; import android.support.design.widget.TabLayout; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import
android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import java.lang.ref.SoftReference; /** * <p/> * author yyw * date 2016/12/22 * version 1.0 * desc */ public class MTableLayout extends TabLayout { private SliderLayout mLayout; private LinearLayout mTabStrip; public
MTableLayout(Context context) { this(context, null, 0); } public MTableLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MTableLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mTabStrip = (LinearLayout) getChildAt(0); removeView(mTabStrip); FrameLayout frameLayout = new FrameLayout(context); addView(frameLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); mLayout = new SliderLayout(context); frameLayout.addView(mLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); frameLayout.addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } @Override public void setupWithViewPager(ViewPager viewPager) { super.setupWithViewPager(viewPager); viewPager.clearOnPageChangeListeners(); viewPager.addOnPageChangeListener(new SliderOnPageChangeListener(this, mLayout)); } public LinearLayout getTabStrip() { return mTabStrip; } public void addTab(TabLayout.Tab tab, boolean setSelected) { super.addTab(tab, setSelected); mLayout.setTotalNum(mTabStrip.getChildCount()); } public void addTab(TabLayout.Tab tab, int position, boolean setSelected) { super.addTab(tab, position, setSelected); mLayout.setTotalNum(mTabStrip.getChildCount()); } @Override public void removeAllTabs() { super.removeAllTabs(); mLayout.setTotalNum(mTabStrip.getChildCount()); } @Override public void removeTabAt(int position) { super.removeTabAt(position); mLayout.setTotalNum(mTabStrip.getChildCount()); } @Override public void removeTab(Tab tab) { super.removeTab(tab); mLayout.setTotalNum(mTabStrip.getChildCount()); } /** * 設定滑塊的背景圖片 * @param resId */ public void setSliderImage(@DrawableRes int resId){ mLayout.setSliderImage(ContextCompat.getDrawable(getContext(),resId)); } /** * Created by yyw on 2016/4/28. * 一個用來顯示當前的index的滑塊 */ public class SliderLayout extends LinearLayout { private int totalNum = 0; private ImageView mSlider; private Drawable mSliderImage; private TabLayout tabLayout; public SliderLayout(Context context) { super(context); init(context); } public Drawable getSliderImage() { return mSliderImage; } public void setSliderImage(Drawable sliderImage) { mSliderImage = sliderImage; mSlider.setImageDrawable(mSliderImage); } private void init(Context context) { mSliderImage = ContextCompat.getDrawable(context,R.drawable.slider); mSlider = new ImageView(context); mSlider.setImageDrawable(mSliderImage); addView(mSlider, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); resetSlider(); } /** * 重新設定滑塊 */ private void resetSlider() { LinearLayout mTabStrip = getTabStrip(); if (mTabStrip == null) return; totalNum = mTabStrip.getChildCount(); if (totalNum > 0) { View firstView = mTabStrip.getChildAt(0); int width = firstView.getMeasuredWidth(); resetSlider(width); } } private LinearLayout getTabStrip() { if (tabLayout == null) return null; if (tabLayout instanceof MTableLayout) { return ((MTableLayout) tabLayout).getTabStrip(); } else { return (LinearLayout) tabLayout.getChildAt(0); } } private void resetSlider(int width) { LayoutParams params = (LayoutParams) mSlider.getLayoutParams(); params.width = width;//重新設定滑塊的大小 params.height = getHeight() / 2; params.gravity = Gravity.CENTER_VERTICAL; mSlider.setPadding(width / 10, 0, width / 10, 0); mSlider.setLayoutParams(params); } public void setupWithTabLayout(TabLayout tabLayout) { this.tabLayout = tabLayout; resetSlider(); } /** * 把滑塊滑動到指定的位置 * * @param position 當前位置 * @param positionOffset 滑動到下一個或上一個位置比例 */ private void setScrollPosition(int position, float positionOffset) { final int roundedPosition = Math.round(position + positionOffset); if (roundedPosition < 0 || roundedPosition >= totalNum) { return; } float scrollX = calculateScrollXForTab(position, positionOffset); scrollTo((int) scrollX, 0); } /** * 計算滑塊需要滑動的距離 * * @param position 當前選擇的位置 * @param positionOffset 滑動位置的百分百 * @return 滑動的距離 */ private int calculateScrollXForTab(int position, float positionOffset) { // TabLayout tabLayout = mTabLayoutRef.get(); if (tabLayout == null) return 0; LinearLayout mTabStrip = getTabStrip(); if (mTabStrip == null) return 0; //當前選擇的View final View selectedChild = mTabStrip.getChildAt(position); //下一個View final View nextChild = position + 1 < mTabStrip.getChildCount() ? mTabStrip.getChildAt(position + 1) : null; //當前選擇的View的寬度 final int selectedWidth = selectedChild != null ? selectedChild.getWidth() : 0; //下一個View的寬度 final int nextWidth = nextChild != null ? nextChild.getWidth() : 0; //當前選擇的View的左邊位置,view的方位 final int left = selectedChild != null ? selectedChild.getLeft() : 0; //計算滑塊需要滑動的距離,左 + ,右 - ; int scrollX = -(left + ((int) ((selectedWidth + nextWidth) * positionOffset * 0.5f))); //現在是把SliderLayout直接放在TableLayout中的所以就不許要考慮TableLayout本身的滑動 /*if (tabLayout.getTabMode() == TabLayout.MODE_SCROLLABLE) {//當為滑動模式的時候TabLayout會有水平方向的滑動 scrollX += tabLayout.getScrollX();//計算在TabLayout有滑動的時候,滑塊相對的滑動距離 }*/ return scrollX; } public void setTotalNum(int totalNum) { this.totalNum = totalNum; resetSlider(); } } public static class SliderOnPageChangeListener extends TabLayout.TabLayoutOnPageChangeListener { private final SoftReference<SliderLayout> mSliderLayoutRef; public SliderOnPageChangeListener(TabLayout tabLayout, SliderLayout layout) { super(tabLayout); mSliderLayoutRef = new SoftReference<SliderLayout>(layout); layout.setupWithTabLayout(tabLayout); } @Override public void onPageScrollStateChanged(int state) { super.onPageScrollStateChanged(state); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { super.onPageScrolled(position, positionOffset, positionOffsetPixels); final SliderLayout layout = mSliderLayoutRef.get(); if (layout != null) { layout.setScrollPosition(position, positionOffset); } } } }

其中比較關鍵的一個類是SliderOnPageChangeListener 這個類繼承的TabLayout.TabLayoutOnPageChangeListener類這個類我們看原始碼(下面)這個是監聽ViewPager滑動選擇的一個介面。我們要做的就是在這個類基礎上進行擴充套件讓SliderLayout也能監聽到ViewPager的滑動。

public static class TabLayoutOnPageChangeListener implements ViewPager.OnPageChangeListener {
        private final WeakReference<TabLayout> mTabLayoutRef;
        private int mPreviousScrollState;
        private int mScrollState;

        public TabLayoutOnPageChangeListener(TabLayout tabLayout) {
            mTabLayoutRef = new WeakReference<>(tabLayout);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            mPreviousScrollState = mScrollState;
            mScrollState = state;
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                int positionOffsetPixels) {
             //省略
            }
        }

        @Override
        public void onPageSelected(int position) {
            //省略
        }

        private void reset() {
            mPreviousScrollState = mScrollState = SCROLL_STATE_IDLE;
        }
    }

計算每次SliderLayout需要滑動的距離的方法是calculateScrollXForTab(int position, float positionOffset)(詳細看原始碼)根據監聽到的ViewPager滑動進行相關的計算並滑動SliderLayout

應用的時候一定要注意viewPager.setOnPageChangeListener(new SliderLayout.SliderOnPageChangeListener(mTabLayout,layout));要在mTabLayout.setupWithViewPager(viewPager);之後呼叫:

public class MainActivity extends AppCompatActivity {
    public static final String TAG = MainActivity.class.getName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewPager viewPager = (ViewPager) findViewById(R.id.vp);
         viewPager.setAdapter(new MViewPagerAdapter(getSupportFragmentManager()));
        mTabLayout.setupWithViewPager(viewPager);
    }

    class MViewPagerAdapter extends FragmentPagerAdapter {
        public  final String[] names = new String[]{"音樂","電影","電視","綜藝","直播","音樂","電影","電視","綜藝","直播"};
        public MViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return BlankFragment.newInstance("param1", "param2");
        }

        @Override
        public int getCount() {
            return 10;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return names[position];
        }
    }
}

佈局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.example.yyw.waterripple.MTableLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/cardview_dark_background"
        app:tabGravity="center"
        app:tabIndicatorColor="#00000000"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="#ff0000"
        app:tabTextColor="#ffffff"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
    <declare-styleable name="SliderLayout">
        <attr name="slider_pic" format="reference" />
    </declare-styleable>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:bottomRightRadius="10dp" />
    <solid android:color="#ffffff" />
</shape>