TabLayout
是Android 的Material Design
包中的一个控件,可以和V4包中的ViewPager
搭配产生一个联动的效果。这里我自定义了一个滑块能够跟随TabLayout
进行滑动选择的SliderLayout
。效果见下图(白色方框):
下面是SliderLayout
的源码:
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.design.widget.TabLayout;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import java.lang.ref.SoftReference;
/**
* Created by yyw on 2016/4/28.
* 一个用来显示当前的index的滑块
*/
public class SliderLayout extends LinearLayout {
private int totalNum = 0;
private Drawable mSliderImage;
private TabLayout mTabLayout;
public SliderLayout(Context context) {
this(context, null);
}
public SliderLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SliderLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setWillNotDraw(false);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.SliderLayout);
mSliderImage = array.getDrawable(R.styleable.SliderLayout_slider_pic);
if (mSliderImage == null) {
mSliderImage = context.getResources().getDrawable(R.drawable.slider);
}
array.recycle();
}
private LinearLayout getTabStrip() {
if (mTabLayout == null) return null;
return (LinearLayout) mTabLayout.getChildAt(0);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
LinearLayout mTabStrip = getTabStrip();
if (mTabStrip == null) return;
totalNum = mTabStrip.getChildCount();
if (totalNum > 0) {
View firstView = mTabStrip.getChildAt(0);
int width = firstView.getMeasuredWidth();
int paddingVertical = getHeight() / 6;
int paddingHorizontal = width / 10;
int bottom = getHeight() - paddingVertical;
int right = width - paddingHorizontal;
mSliderImage.setBounds(paddingVertical, paddingHorizontal, right, bottom);
mSliderImage.draw(canvas);
}
}
public void setupWithTabLayout(TabLayout tabLayout) {
this.mTabLayout = tabLayout;
}
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);
}
}
}
/**
* 把滑块滑动到指定的位置
*
* @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) {
if (mTabLayout == 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 (mTabLayout.getTabMode() == TabLayout.MODE_SCROLLABLE) {//当为滑动模式的时候TabLayout会有水平方向的滑动
scrollX += mTabLayout.getScrollX();//计算在TabLayout有滑动的时候,滑块相对的滑动距离
}
return scrollX;
}
public void setSliderImage(Drawable sliderImage) {
mSliderImage = sliderImage;
invalidate();
}
}
其中比较关键的一个类是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 mViewPager = (ViewPager) findViewById(R.id.container);
SliderLayout sliderLayout = (SliderLayout) findViewById(R.id.sl);
final TabLayout mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
mViewPager.setAdapter(mSectionsPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mViewPager.clearOnPageChangeListeners();
mViewPager.addOnPageChangeListener(new SliderLayout.SliderOnPageChangeListener(mTabLayout, sliderLayout));
}
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">
<FrameLayout
android:layout_width="match_parent"
android:background="@color/cardview_dark_background"
android:layout_height="50dp">
<com.tongyan.tablayoutdemo.SliderLayout
android:id="@+id/sl"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:tabGravity="fill"
app:tabIndicatorColor="#00000000"
app:tabMode="fixed"
app:tabSelectedTextColor="#ff0000"
app:tabTextColor="#ffffff"/>
</FrameLayout>
<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>