根据老师讲课写下来的,虽然老师讲课只用了2个小时,但自己跟着写和修改却用了整整一天啊,这个导航用的地方确实还真多,写上注释,记录下来!
1.主要的自定义的类,ViewPagerIndicator继承自LinearLayout
package cq.cake.customview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.CornerPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import cq.cake.indicator.R; /** * My Application -- cq.cake.customview * Created by Small Cake on 2016/3/17 10:45. */ public class ViewPagerIndicator extends LinearLayout { //绘制三角形 private Paint mPaint; //三角形的路径 private Path mPath; //三角形的宽高 private int mTriangleWidth; private int mTriangleHeight; //三角形的宽度, private static final float RADIO_TRIANGLE_WIDTH = 1/6F; //三角形底边的最大宽度 private final int DIMENSION_TRIANGLE_WIDTH_MAX = (int) (getScreenWidth()/3*RADIO_TRIANGLE_WIDTH); //三角形初始化偏移位置 private int mInitTranslationX; //移动时的位置 private int mTranslationX; //自定义属性 private int mTabVisibleCount; private static final int COUNT_DEFAULT_TAB =4; private int screenWidth; //根据标题来动态的添加标题 private List<String> mTitles; private static final int COLOR_TEXT_NORMAL = 0X77FFFFFF; private static final int COLOR_TEXT_HIGHLIGHT = 0xFFFFFFFF; public ViewPagerIndicator(Context context) { this(context, null); } public ViewPagerIndicator(Context context, AttributeSet attrs) { super(context, attrs); //获取指定的tab数量 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator); mTabVisibleCount = a.getInt(R.styleable.ViewPagerIndicator_visible_tab_count,COUNT_DEFAULT_TAB); if (mTabVisibleCount<0){ mTabVisibleCount = COUNT_DEFAULT_TAB; } //释放资源 a.recycle(); //初始化画笔 mPaint = new Paint(); mPaint.setAntiAlias(true);//设置抗锯齿 mPaint.setColor(Color.parseColor("#ffffff")); //设置样式为实心 mPaint.setStyle(Paint.Style.FILL); //防止三角形太尖锐,设置拐角处为3的圆角 mPaint.setPathEffect(new CornerPathEffect(3)); } @Override protected void dispatchDraw(Canvas canvas) { canvas.save(); //移动 canvas.translate(mInitTranslationX + mTranslationX, getHeight() + 2); canvas.drawPath(mPath, mPaint); canvas.restore(); super.dispatchDraw(canvas); } /** * 在这个方法里面设置三角形的大小 * 控件的宽高发生变化时就会调用此方法 * @param w * @param h * @param oldw * @param oldh */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); //三角形底边的宽度 mTriangleWidth = (int) (w/mTabVisibleCount*RADIO_TRIANGLE_WIDTH); mTriangleWidth = Math.min(mTriangleWidth,DIMENSION_TRIANGLE_WIDTH_MAX); //三角形初始值的偏移量 mInitTranslationX = w/mTabVisibleCount/2-mTriangleWidth/2; initTriangle(); } /** * 当xml加载完成后调用此方法 */ @Override protected void onFinishInflate() { super.onFinishInflate(); //得到子菜单个数 int cCount = getChildCount(); if (cCount==0)return; for (int i = 0; i < cCount; i++) { View view = getChildAt(i); LinearLayout.LayoutParams lp = (LayoutParams) view.getLayoutParams(); lp.weight = 0; lp.width = getScreenWidth()/mTabVisibleCount; view.setLayoutParams(lp); } setTabItemClick(); } private void initTriangle() { //初始化高度 mTriangleHeight = mTriangleWidth/2; mPath = new Path(); mPath.moveTo(0, 0); mPath.lineTo(mTriangleWidth, 0); mPath.lineTo(mTriangleWidth / 2, -mTriangleHeight); //路径的闭合 mPath.close(); } /** * 指示器跟随手指移动进行滚动 * @param position * @param offset */ public void scroll(int position, float offset) { int tabWidth = getWidth()/mTabVisibleCount; mTranslationX = (int) (tabWidth*(offset+position)); //当tab移动到最后一个时 if (position>=(mTabVisibleCount - 2)&&offset>0&&getChildCount()>mTabVisibleCount){ if (mTabVisibleCount!=1){ this.scrollTo( (position-(mTabVisibleCount-2))*tabWidth+(int)(tabWidth*offset) ,0); }else{ this.scrollTo(position*tabWidth+(int)(tabWidth*offset),0); } } //进行重绘 invalidate(); } public int getScreenWidth() { WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(outMetrics); return outMetrics.widthPixels; } public void setTabItemTitles(List<String> titles) { if (titles!=null&&titles.size()>0){ this.removeAllViews(); mTitles = titles; for (String title:mTitles){ addView(generateTextView(title)); } } setTabItemClick(); } /** * 设置显示的tab的数量 * @param count */ public void setVisibleTabCount(int count){ mTabVisibleCount = count; } private View generateTextView(String title){ TextView tv = new TextView(getContext()); LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT); lp.width = getScreenWidth()/mTabVisibleCount; tv.setText(title); tv.setGravity(Gravity.CENTER); tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,16); tv.setTextColor(COLOR_TEXT_NORMAL); tv.setLayoutParams(lp); return tv; } private ViewPager mViewPager; /** * 设置关联的ViewPager * @param viewPager * @param pos */ public void setViewPager(ViewPager viewPager, final int pos){ mViewPager = viewPager; mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { //positionOffset是一个梯度值 @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { //tabWidth*positionOffset+positioin*tabWidth//移动时的偏移量 scroll(position, positionOffset); if (mListener != null) { mListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } @Override public void onPageSelected(int position) { if (mListener != null) { mListener.onPageSelected(position); } heightLightTextView(position); } @Override public void onPageScrollStateChanged(int state) { if (mListener != null) { mListener.onPageScrollStateChanged(state); } } }); mViewPager.setCurrentItem(pos); heightLightTextView(pos); } public interface PageOnChangeListener{ public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); public void onPageSelected(int position); public void onPageScrollStateChanged(int state); } public PageOnChangeListener mListener; public void setOnPageChangerListener(PageOnChangeListener listener){ this.mListener = listener; } /** * 重置文本颜色 */ private void resetTextViewColor(){ for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); if (view instanceof TextView){ ((TextView) view).setTextColor(COLOR_TEXT_NORMAL); } } } /** * 高亮某个tab的文本 * @param pos */ private void heightLightTextView(int pos){ resetTextViewColor(); View view = getChildAt(pos); if (view instanceof TextView){ ((TextView) view).setTextColor(COLOR_TEXT_HIGHLIGHT); } } /** * 设置tab的点击事件 */ private void setTabItemClick(){ int cCount = getChildCount(); for (int i = 0; i < cCount; i++) { final int j = i; View view = getChildAt(i); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mViewPager.setCurrentItem(j); } }); } } }2.用于装载的Fragment容器
package cq.cake.customview; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * My Application -- cq.cake.customview * Created by Small Cake on 2016/3/17 11:32. */ public class VpSimpleFragment extends Fragment { private String mTilte; private static final String BUNDLE_TITLE = "title"; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle bundle = getArguments(); if (bundle!=null){ mTilte =bundle.getString(BUNDLE_TITLE); } TextView tv = new TextView(getActivity()); tv.setText(mTilte); tv.setGravity(Gravity.CENTER); return tv; } public static VpSimpleFragment newInstance(String title){ Bundle bundle = new Bundle(); bundle.putString(BUNDLE_TITLE,title); VpSimpleFragment fragment = new VpSimpleFragment(); fragment.setArguments(bundle); return fragment; } }
package cq.cake.indicator; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import cq.cake.customview.ViewPagerIndicator; import cq.cake.customview.VpSimpleFragment; public class MainActivity extends FragmentActivity { private ViewPager mViewPager; private ViewPagerIndicator mIndicator; private List<String> mTitles = Arrays.asList("短信1","收藏2","推荐3","短信4","收藏5","推荐6","短信7","收藏8","推荐9"); private List<VpSimpleFragment> mContents = new ArrayList<VpSimpleFragment>(); private FragmentPagerAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); initView(); initData(); mIndicator.setVisibleTabCount(3); mIndicator.setTabItemTitles(mTitles); mViewPager.setAdapter(mAdapter); mIndicator.setViewPager(mViewPager,0); mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { //positionOffset是一个梯度值 @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { //tabWidth*positionOffset+positioin*tabWidth//移动时的偏移量 mIndicator.scroll(position, positionOffset); } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }); } private void initData() { for (String title:mTitles){ VpSimpleFragment fragment = VpSimpleFragment.newInstance(title); mContents.add(fragment); } mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public Fragment getItem(int position) { return mContents.get(position); } @Override public int getCount() { return mContents.size(); } }; } private void initView() { mViewPager = (ViewPager) findViewById(R.id.viewpager); mIndicator = (ViewPagerIndicator) findViewById(R.id.indicator); } }
<?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" android:orientation="vertical" android:background="#ffffff" xmlns:cake ="http://schemas.android.com/apk/res-auto" tools:context="cq.cake.indicator.MainActivity"> <cq.cake.customview.ViewPagerIndicator android:orientation="horizontal" android:background="#383737" android:id="@+id/indicator" android:layout_width="match_parent" cake:visible_tab_count="4" android:layout_height="45dp"> </cq.cake.customview.ViewPagerIndicator> <android.support.v4.view.ViewPager android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@+id/viewpager" /> </LinearLayout>
源码地址:ViewPager滑动导航