码迷,mamicode.com
首页 > 其他好文 > 详细

ViewPager + Fragment 实现标签的滚动效果

时间:2016-05-03 18:09:41      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

  • 效果图技术分享
  • 点击标签,指示线滑动到当前的标签下。
  • 用到的技术: activity中添加 fragement, ViewPager, 自定义绘制view
    -

Activity中动态添加碎片的步骤

  • 创建待添加的碎片实例。
    获取到FragmentManager
    开启一个事务
    向容器中加入一个碎片
    提交事务

因为这里涉及到了下面RadioButton的点击处理,关键的就是虚线框的东西

package xiaoxu.com.lifeservice.avtivity;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.app.FragmentTransaction;


import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.util.ArrayList;
import java.util.Arrays;


import xiaoxu.com.lifeservice.R;
import xiaoxu.com.lifeservice.frag.FirstPageFrag;
import xiaoxu.com.lifeservice.frag.TextFrag;

public class MainActivity extends BaseActivity {
    String[] fragStr = {"FirstPageFrag"};
    RadioButton firstPageBtn;
    ArrayList<String> fragTag;
    int mCurrIndex = 0;
    FragmentManager fragManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragManager = getSupportFragmentManager();

        if(savedInstanceState == null) {

            initData();
            initView();
        } else {


        }
    }

    private void initView() {

        firstPageBtn = (RadioButton) findViewById(R.id.firstPageBtn);
        firstPageBtn.setChecked(true);

        RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_btn);
        radioGroup.setOnCheckedChangeListener(radioListener);

        showFragment();
    }
//向容器中添加碎片,并显示。
//------------------------------------------------
    private void showFragment() {
        if(mCurrIndex == 3 ) {
            return;
        }
        android.support.v4.app.FragmentTransaction transaction = fragManager.beginTransaction();

        Fragment frag = fragManager.findFragmentByTag(fragTag.get(mCurrIndex));
        if (frag == null) {

            frag = getInstance();
        }

        for (int i = 0; i < fragTag.size(); i++) {

            Fragment f = fragManager.findFragmentByTag(fragTag.get(i));
            if (f != null && f.isAdded()) {

                transaction.hide(f);//隐藏当前的Fragment,仅仅是设为不可见,并不会销毁
            }
        }

        if (frag.isAdded()) {

            transaction.show(frag);
        } else {

            transaction.add(R.id.content_Area, frag, fragTag.get(mCurrIndex));
        }
        transaction.commitAllowingStateLoss();
        fragManager.executePendingTransactions();

    }
//---------------------------------------------
    private void initData() {
        mCurrIndex = 0;
        fragTag = new ArrayList<>(Arrays.asList(fragStr));
    }

    private RadioGroup.OnCheckedChangeListener radioListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.firstPageBtn:
                    mCurrIndex = 0;
                    break;
                case R.id.listBtn:
                    mCurrIndex = 1;
                    break;
                case R.id.dataBtn:
                    mCurrIndex = 2;
                    break;
                case R.id.myBtn:
                    mCurrIndex = 3;
                    break;
            }

        }
    };


    public Fragment getInstance() {

        //if(mCurrIndex == 0 ) {

            return new FirstPageFrag();
       // }

       // return null;
    }
}
  • 附上activity中用到的xml文件。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".avtivity.MainActivity"
    android:orientation="vertical"
    android:fitsSystemWindows="true">
    <include layout="@layout/layout_title_head"/>

    <FrameLayout
        android:id="@+id/content_Area"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

    </FrameLayout>

    <include layout="@layout/layout_footer"/>
</LinearLayout>

-接下来创建一个碎片,并从xml中获取到ViewPager 和 创建自定义view的实例。

package xiaoxu.com.lifeservice.frag;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import xiaoxu.com.lifeservice.R;
import xiaoxu.com.lifeservice.ui.tabStrip.PagerSlidingTabStrip;


/**
 * Created by Administrator on 2016/4/30.
 */
public class FirstPageFrag extends Fragment {

    ViewPager pager;
    PagerSlidingTabStrip tabStrip;
    final String[] TITLE = {"首页", "新闻", "小说", "更多"};

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_pager, null);
        pager = (ViewPager) view.findViewById(R.id.pager);
        tabStrip = (PagerSlidingTabStrip) view.findViewById(R.id.tab);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        pager.setAdapter(new NewsAdapter(getChildFragmentManager()));

        int pagerMargin =
                (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
        pager.setPageMargin(pagerMargin);
        tabStrip.setPager(pager);

    }

    class NewsAdapter extends FragmentPagerAdapter {
        public NewsAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return new TextFrag();//根据标签的position返回指定的frag。
        }

        @Override
        public int getCount() {
            return TITLE.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLE[position % TITLE.length];
        }


    }
}
  • 这里用到的xml文件如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:title="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <xiaoxu.com.lifeservice.ui.tabStrip.PagerSlidingTabStrip
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        title:pstsDividerColor="#CC0000"
        title:pstsIndicatorColor="#003399"
        title:pstsIndicatorHeight="2dp"
        title:pstsTabPaddingLeftRight="12dp"
        title:pstsUnderlineColor="#404040"
        title:pstsUnderlineHeight="0.5dp"
        title:selectedTabTextColor="#003399"
        title:tabTextColor="#000000"
        title:tabTextSize="8sp">

    </xiaoxu.com.lifeservice.ui.tabStrip.PagerSlidingTabStrip>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

    </android.support.v4.view.ViewPager>


</LinearLayout>
  • PagerSlidingTabStrip 自定义的view,这个布局将占据着上一个xml 中id 为 content_Area的空间。
  • 这里title:都是自定义的属性。自定义属性如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="pagerSlidTabStrip">

        <attr name="pstsIndicatorColor" format="color" />
        <attr name="pstsUnderlineColor" format="color" />
        <attr name="pstsDividerColor" format="color" />
        <attr name="pstsIndicatorHeight" format="dimension" />
        <attr name="pstsUnderlineHeight" format="dimension" />
        <attr name="pstsDividerPadding" format="dimension" />
        <attr name="pstsTabPaddingLeftRight" format="dimension" />
        <attr name="pstsScrollOffset" format="dimension"/>
        <attr name="pstsTabBackground" format="dimension" />
       <attr name="pstsShouldExpand" format="boolean" />
        <attr name="pstsTextAllCaps" format="boolean" />
        <attr name="tabTextSize" format="dimension" />
        <attr name="tabTextColor" format="color" />
        <attr name="selectedTabTextColor" format="color" />

    </declare-styleable>


</resources>

  • 自定义view 绘制指示线,和viewPager之间的占位线。
package xiaoxu.com.lifeservice.ui.tabStrip;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.net.IDN;
import java.util.Locale;

import xiaoxu.com.lifeservice.R;

/**
 * Created by Administrator on 2016/5/1.
 * 指示标签
 */

/**
 * pstsIndicatorColor      指示器颜色
 * pstsUnderlineColor      在视图底部占位线的颜色
 * pstsDividerColor        标签之间分隔线的颜色
 * pstsIndicatorHeight     指示器的高度
 * pstsUnderlineHeight     在视图的底部占位线的高度
 * pstsDividerPadding      Top and bottom padding of the dividers
 * pstsTabPaddingLeftRight 左右标签间距
 * pstsScrollOffset    ·   指示器相对被选中的标签的偏移
 * pstsTabBackground       标签的背景,应该是一个StateListDrawable
 * pstsShouldExpand        如果设置为true,每个标签都给予同样的weight,默认为false
 * pstsTextAllCaps         如果为真,所有选项卡标题都是大写,默认为true
 * tabTextSize             标签的文字大小
 * tabTextColor            标签的文字颜色
 * selectedTabTextColor    被选中标签的文字颜色
 */
public class PagerSlidingTabStrip extends HorizontalScrollView {

    private LinearLayout.LayoutParams defaultTabLayoutParams;
    private LinearLayout.LayoutParams expandedTabLayoutParams;


    public ViewPager.OnPageChangeListener delegatePageListener;

    private LinearLayout tabsContainer;
    private ViewPager pager;

    private int tabCount;

    private int currentPosition = 0;
    private int selectedPosition = 0; //当前选中项
    private float currentPositionOffset = 0f;

    private Paint rectPaint;
    private Paint dividerPaint;

    private int indicatorColor = 0xFF666666;
    private int underlineColor = 0x1A000000;
    private int dividerColor = 0x1A000000;
    private int indicatorHeight = 8;//指示器的高度

    private boolean shouldExpand = false;
    private boolean textAllCaps = true;

    private int scrollOffset = 52;

    private int underlineHeight = 2;
    private int dividerPadding = 12;
    private int tabPadding = 24;
    private int dividerWidth = 1;

    private int tabTextSize = 12;
    private int tabTextColor = 0xFF666666;
    private int selectedTabTextColor = 0xFF666666;
    private Typeface tabTypeface = null;
    private int tabTypefaceStyle = Typeface.NORMAL;

    private int lastScrollX = 0;

    private int tabBackgroundResId = R.drawable.tab_strip_background_tab;

    private Locale locale;


    public PagerSlidingTabStrip(Context context, AttributeSet attrs) {
        super(context, attrs);

        setFillViewport(true);
        setWillNotDraw(false);

        tabsContainer = new LinearLayout(context);
        tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
        tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        addView(tabsContainer);

        DisplayMetrics dm = getResources().getDisplayMetrics();
        //int ---> dp
        scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
        indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
        underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
        dividerPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm);
        tabPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm);
        dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm);
        tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm);

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.pagerSlidTabStrip);
        //选择标签的颜色
        indicatorColor = ta.getColor(R.styleable.pagerSlidTabStrip_pstsIndicatorColor, indicatorColor);
        //占位线颜色
        underlineColor = ta.getColor(R.styleable.pagerSlidTabStrip_pstsUnderlineColor, underlineColor);
        //标签之间的分隔线颜色
        dividerColor = ta.getColor(R.styleable.pagerSlidTabStrip_pstsDividerColor, dividerColor);
        //指示器的高度
        indicatorHeight = ta.getDimensionPixelSize(R.styleable.pagerSlidTabStrip_pstsIndicatorHeight, indicatorHeight);
        //占位线的高度
        underlineHeight = ta.getDimensionPixelSize(R.styleable.pagerSlidTabStrip_pstsUnderlineHeight, underlineHeight);
        //Top and bottom padding of the dividers
        dividerPadding = ta.getDimensionPixelSize(R.styleable.pagerSlidTabStrip_pstsDividerPadding, dividerPadding);
        //左右标签间距
        tabPadding = ta.getDimensionPixelSize(R.styleable.pagerSlidTabStrip_pstsTabPaddingLeftRight, tabPadding);
        //标签选中移动的值
        scrollOffset = ta.getDimensionPixelSize(R.styleable.pagerSlidTabStrip_pstsScrollOffset, scrollOffset);
        //标签的背景
        tabBackgroundResId = ta.getResourceId(R.styleable.pagerSlidTabStrip_pstsTabBackground, tabBackgroundResId);
        //如果设置为true,每个标签都给予同样的weight,默认为false
        shouldExpand = ta.getBoolean(R.styleable.pagerSlidTabStrip_pstsShouldExpand, shouldExpand);
        //如果为真,所有选项卡标题都是大写,默认为true
        textAllCaps = ta.getBoolean(R.styleable.pagerSlidTabStrip_pstsTextAllCaps, textAllCaps);
        //标签字体大小
        tabTextSize = ta.getDimensionPixelSize(R.styleable.pagerSlidTabStrip_tabTextSize, tabTextSize);
        //标签字体颜色
        tabTextColor = ta.getColor(R.styleable.pagerSlidTabStrip_tabTextColor, tabTextColor);
        //选中的字体颜色
        selectedTabTextColor = ta.getColor(R.styleable.pagerSlidTabStrip_selectedTabTextColor, selectedTabTextColor);

        rectPaint = new Paint();
        rectPaint.setAntiAlias(true);
        rectPaint.setStyle(Paint.Style.FILL);

        dividerPaint = new Paint();
        dividerPaint.setAntiAlias(true);
        dividerPaint.setStyle(Paint.Style.FILL);

        defaultTabLayoutParams =
                new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        expandedTabLayoutParams =
                new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);

        if (locale == null) {
            locale = getResources().getConfiguration().locale;
        }
    }

    public interface IconTabProvider {
        int getPageIconResId(int position);
    }

    public void setPager(ViewPager pager) {
        this.pager = pager;

        if (pager.getAdapter() == null) {

            throw new IllegalStateException("page does not have Adapter ");
        }

        pager.addOnPageChangeListener(pageListener);

        notifyDataSetChange();

    }

    private void notifyDataSetChange() {
        tabsContainer.removeAllViews();

        tabCount = pager.getAdapter().getCount();
        for (int i = 0; i < tabCount; i++) {

            if (pager.getAdapter() instanceof IconTabProvider) {

                addIconTab(i, ((IconTabProvider) pager.getAdapter()).getPageIconResId(i));
            } else {

                addTextTab(i, pager.getAdapter().getPageTitle(i));
            }

        }

        updateTabStyles();

        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                getViewTreeObserver().removeOnGlobalLayoutListener(this);

                currentPosition = pager.getCurrentItem();
                scroll2Child(currentPosition, 0);
            }
        });
    }

    private void addTextTab(int i, CharSequence pageTitle) {

        TextView tv = new TextView(getContext());
        tv.setSingleLine();
        tv.setText(pageTitle);
        tv.setTextSize(tabTextSize);
        tv.setGravity(Gravity.CENTER);
        addTab(tv, i);
    }

    private void addIconTab(int i, int pageIconResId) {

        ImageButton imageBtn = new ImageButton(getContext());
        imageBtn.setImageResource(pageIconResId);

        addTab(imageBtn, i);
    }

    private void addTab(final View view, final int position) {

        view.setFocusable(true);
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                pager.setCurrentItem(position);
            }
        });
        tabsContainer.addView(view, shouldExpand ? defaultTabLayoutParams : expandedTabLayoutParams);
        tabsContainer.setPadding(tabPadding, 0, tabPadding, 0);
    }

    private ViewPager.OnPageChangeListener pageListener = new ViewPager.OnPageChangeListener() {

     /**
      * 滚动完成后回调
      * */
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            currentPositionOffset = positionOffset;
            currentPosition = position;

            scroll2Child(position, (int) positionOffset * tabsContainer.getChildAt(position).getWidth());
            invalidate();

            if (delegatePageListener != null) {

                delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

        }

        @Override
        public void onPageSelected(int position) {

            selectedPosition = position;
            updateTabStyles();
            if (delegatePageListener != null) {

                delegatePageListener.onPageSelected(position);
            }

        }

        @Override
        public void onPageScrollStateChanged(int state) {

            if (state == ViewPager.SCROLL_STATE_IDLE) {

                scroll2Child(pager.getCurrentItem(), 0);
            }

        }
    };

    public ViewPager getPager() {
        return pager;
    }

    public ViewPager.OnPageChangeListener getDelegatePageListener() {
        return delegatePageListener;
    }

    public void setDelegatePageListener(ViewPager.OnPageChangeListener delegatePageListener) {

        this.delegatePageListener = delegatePageListener;
        updateTabStyles();
    }

    public int getCurrentPosition() {
        return currentPosition;
    }

    public void setCurrentPosition(int currentPosition) {
        this.currentPosition = currentPosition;
        updateTabStyles();
    }

    public int getSelectedPosition() {
        return selectedPosition;
    }

    public void setSelectedPosition(int selectedPosition) {
        this.selectedPosition = selectedPosition;
        updateTabStyles();
    }

    public float getCurrentPositionOffset() {
        return currentPositionOffset;
    }

    public void setCurrentPositionOffset(float currentPositionOffset) {
        this.currentPositionOffset = currentPositionOffset;
        updateTabStyles();
    }

    public int getIndicatorColor() {
        return indicatorColor;
    }

    public void setIndicatorColor(int indicatorColor) {
        this.indicatorColor = indicatorColor;
        updateTabStyles();
    }

    public int getUnderlineColor() {
        return underlineColor;
    }

    public void setUnderlineColor(int underlineColor) {
        this.underlineColor = underlineColor;
        updateTabStyles();
    }

    public int getDividerColor() {
        return dividerColor;
    }

    public void setDividerColor(int dividerColor) {
        this.dividerColor = dividerColor;
        updateTabStyles();
    }

    public int getIndicatorHeight() {
        return indicatorHeight;
    }

    public void setIndicatorHeight(int indicatorHeight) {
        this.indicatorHeight = indicatorHeight;
        updateTabStyles();
    }

    public boolean isShouldExpand() {
        return shouldExpand;
    }

    public void setShouldExpand(boolean shouldExpand) {
        this.shouldExpand = shouldExpand;
        updateTabStyles();
    }

    public boolean isTextAllCaps() {
        return textAllCaps;
    }

    public void setTextAllCaps(boolean textAllCaps) {
        this.textAllCaps = textAllCaps;
        updateTabStyles();
    }

    public int getScrollOffset() {
        return scrollOffset;
    }

    public void setScrollOffset(int scrollOffset) {
        this.scrollOffset = scrollOffset;
        updateTabStyles();

    }

    public int getUnderlineHeight() {
        return underlineHeight;
    }

    public void setUnderlineHeight(int underlineHeight) {
        this.underlineHeight = underlineHeight;
        updateTabStyles();
    }

    public int getDividerPadding() {
        return dividerPadding;
    }

    public void setDividerPadding(int dividerPadding) {
        this.dividerPadding = dividerPadding;
        updateTabStyles();
    }

    public int getTabPadding() {
        return tabPadding;
    }

    public void setTabPadding(int tabPadding) {
        this.tabPadding = tabPadding;
        updateTabStyles();
    }

    public int getDividerWidth() {
        return dividerWidth;
    }

    public void setDividerWidth(int dividerWidth) {
        this.dividerWidth = dividerWidth;
        updateTabStyles();
    }

    public int getTabTextSize() {
        return tabTextSize;
    }

    public void setTabTextSize(int tabTextSize) {
        this.tabTextSize = tabTextSize;
        updateTabStyles();
    }

    public int getTabTextColor() {
        return tabTextColor;
    }

    public void setTabTextColor(int tabTextColor) {
        this.tabTextColor = tabTextColor;
        updateTabStyles();
    }

    public int getSelectedTabTextColor() {
        return selectedTabTextColor;
    }

    public void setSelectedTabTextColor(int selectedTabTextColor) {
        this.selectedTabTextColor = selectedTabTextColor;
        updateTabStyles();
    }

    public Typeface getTabTypeface() {
        return tabTypeface;
    }

    public void setTypeface(Typeface typeface, int style) {
        this.tabTypeface = typeface;
        this.tabTypefaceStyle = style;
        updateTabStyles();
    }

    public int getTabTypefaceStyle() {
        return tabTypefaceStyle;
    }

    public void setTabTypefaceStyle(int tabTypefaceStyle) {
        this.tabTypefaceStyle = tabTypefaceStyle;
        updateTabStyles();
    }

    /**
     * 更新选中时标签的状态
     */
    private void updateTabStyles() {
        for (int i = 0; i < tabCount; i++) {

            View v = tabsContainer.getChildAt(i);
           v.setBackgroundResource(tabBackgroundResId);

            if (v instanceof TextView) {

                TextView textView = (TextView) v;
                textView.setTextColor(tabTextColor);
                textView.setTextSize(tabTextSize);
                textView.setGravity(Gravity.CENTER);

                textView.setTypeface(tabTypeface,tabTypefaceStyle);
                if (textAllCaps) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {

                        textView.setAllCaps(true);
                    } else {

                        textView.setText(textView.getText().toString().toUpperCase(locale));
                    }

                }

                if (i == selectedPosition)

                    textView.setTextColor(selectedTabTextColor);

            }
        }


    }

    /**
     * @param  position 当前的标题的position
     * @param offset 滚动的偏移量
     * */

    private void scroll2Child(int position, int offset) {
        if (tabCount == 0) {
            return;
        }
        int newX = tabsContainer.getChildAt(position).getLeft() + offset;

        if (offset > 0 || offset > 0) {

            newX -= scrollOffset;

        }

        if (newX != lastScrollX) {

            scrollTo(newX, 0);
            lastScrollX = newX;
        }
    }

    /**
     * 绘制占位线 和 指示线
     * */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (isInEditMode() || tabCount == 0) {

            return;
        }

        rectPaint.setColor(underlineColor);
        int height = getHeight();
        //画底线
        canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint);

        //选中标签下的线
        rectPaint.setColor(indicatorColor);
        View currentTab = tabsContainer.getChildAt(currentPosition);

        float lineLeft = currentTab.getLeft();
        float lineRight = currentTab.getRight();
        //在满足偏移量大于0 ,且有下一个标签的时候
        if (currentPositionOffset > 0 && currentPosition < tabCount - 1) {

            View nextTab = tabsContainer.getChildAt(currentPosition + 1);
            int nextTabLeft = nextTab.getLeft();
            int nextTabRight = nextTab.getRight();

            lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
            lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);

        }

        canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);

        // 分割线
        dividerPaint.setColor(dividerColor);
        for (int i = 0; i < tabCount - 1; i++) {
            View tab = tabsContainer.getChildAt(i);
            canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding, dividerPaint);
        }

    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        SaveState saveState = (SaveState) state;
        super.onRestoreInstanceState(saveState.getSuperState());

        selectedPosition = saveState.currentPosition;
        requestLayout();
    }

    /**
     * 系统回收activity之前回调
     * */
    @Override
    protected Parcelable onSaveInstanceState() {
        Parcelable parcelable = super.onSaveInstanceState();
        SaveState saveState = new SaveState(parcelable);

        saveState.currentPosition = selectedPosition;
        return saveState;
    }

    static class SaveState extends BaseSavedState {

        int currentPosition;

        public SaveState(Parcelable source) {
            super(source);
        }

        private SaveState(Parcel in) {
            super(in);
            currentPosition = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);

            out.writeInt(flags);
        }

        public static final Creator<SaveState> CREATOR = new Creator<SaveState>() {
            @Override
            public SaveState createFromParcel(Parcel source) {
                return new SaveState(source);
            }

            @Override
            public SaveState[] newArray(int size) {
                return new SaveState[size];
            }
        };


    }

}

ViewPager + Fragment 实现标签的滚动效果

标签:

原文地址:http://blog.csdn.net/qq_32223565/article/details/51303148

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!