Android开发:史上最简单方便的viewpager加indicator的方法

开发Android应用的时候,每次给viewpager加indicator的时候,是不是感觉到很无力呢,看看JakeWharton大神的github,要么要应用library,要么把code加到自己的项目中,还要加attrs,加各种value,比如colors,strings,其实超过90%以上的时候,我们的需要其实很简单,只是在底部的中间加上指示圆点,而且JakeWharton大神的默认的是空心圆圈,还要在onDraw中改成实心的圆形,是不是厌烦啦,每次都要这么麻烦,好了,终极简单的解决方法出来了,想看效果:

当然,这个效果照搬别人的图,不过实现这个效果,我用了超级简单的方法,一劳永逸:

只要三个步骤,复制粘贴,再复制粘贴,然后在activity中写几行代码即可。

  • 第一步,复制,粘贴

新建一个类,叫做CircleIndicatorHelper,然后复制如下的代码进去:

public class CircleIndicatorHelper {
	private CirclePageIndicator mCircleIndicator;
	private Context mContext;

	public CircleIndicatorHelper(Context context) {
		mCircleIndicator = new CirclePageIndicator(context);
		mContext = context;
	}

	public void setViewpager(ViewPager viewPager) {
		ViewGroup parentView = (ViewGroup) viewPager.getParent();
		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
		lp.setMargins(0, 0, 0, dpToPx(8));
		mCircleIndicator.setLayoutParams(lp);
		parentView.addView(mCircleIndicator);
		mCircleIndicator.setViewPager(viewPager);
	}

	public void setFillColor(String colorString) {
		int color = Color.parseColor(colorString);
		mCircleIndicator.setFillColor(color);
	}

	public void setDefaultColor(String colorString) {
		int color = Color.parseColor(colorString);
		mCircleIndicator.setDefaultColor(color);
	}

	public void setRadius(int radius) {
		mCircleIndicator.setRadius(dpToPx(radius));
	}

	private int dpToPx(int dp) {
		DisplayMetrics resourec = mContext.getResources().getDisplayMetrics();
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resourec);
	}
}
  • 第二部,再新建一个类,名字叫复制,粘贴
public class CirclePageIndicator extends View{
    private static final int INVALID_POINTER = -1;

    private float mRadius;
//    private final Paint mPaintPageFill = new Paint(ANTI_ALIAS_FLAG);
    private final Paint mPaintStroke = new Paint(ANTI_ALIAS_FLAG);
    private final Paint mPaintFill = new Paint(ANTI_ALIAS_FLAG);
    private ViewPager mViewPager;
    private ViewPager.OnPageChangeListener mListener;
    private int mCurrentPage;
    private int mSnapPage;
    private float mPageOffset;
    private int mScrollState;
    private int mOrientation;
    private boolean mCentered;
    private boolean mSnap;

    private float cicleSpace;

    public CirclePageIndicator(Context context) {
        this(context, null);
    }

    public CirclePageIndicator(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CirclePageIndicator(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        if (isInEditMode()) return;

        final Resources res = getResources();
        final int defaultFillColor = Color.parseColor("#7F7F7F");
        final int defaultStrokeColor = Color.parseColor("#D0D0D0");
        final float defaultRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, res.getDisplayMetrics());
        mCentered = true;

        mPaintStroke.setStyle(Style.FILL);
        mPaintStroke.setColor(defaultStrokeColor);
        mPaintFill.setStyle(Style.FILL);
        mPaintFill.setColor(defaultFillColor);
        mRadius = defaultRadius;

        cicleSpace = mRadius*3;

    }

    public void setCentered(boolean centered) {
        mCentered = centered;
        invalidate();
    }

    public boolean isCentered() {
        return mCentered;
    }

    public void setDefaultColor(int strokeColor) {
        mPaintStroke.setColor(strokeColor);
        invalidate();
    }

    public void setFillColor(int fillColor) {
    	mPaintFill.setColor(fillColor);
    	invalidate();
    }

    public void setRadius(float radius) {
        mRadius = radius;
        cicleSpace = radius*3;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mViewPager == null) {
            return;
        }
        final int count = mViewPager.getAdapter().getCount();
        if (count == 0) {
            return;
        }

        if (mCurrentPage >= count) {
            setCurrentItem(count - 1);
            return;
        }

        int longSize;
        int longPaddingBefore;
        int longPaddingAfter;
        int shortPaddingBefore;
        if (mOrientation == HORIZONTAL) {
            longSize = getWidth();
            longPaddingBefore = getPaddingLeft();
            longPaddingAfter = getPaddingRight();
            shortPaddingBefore = getPaddingTop();
        } else {
            longSize = getHeight();
            longPaddingBefore = getPaddingTop();
            longPaddingAfter = getPaddingBottom();
            shortPaddingBefore = getPaddingLeft();
        }

        final float shortOffset = shortPaddingBefore + mRadius;
        float longOffset = longPaddingBefore + mRadius;
        if (mCentered) {
            longOffset += ((longSize - longPaddingBefore - longPaddingAfter) / 2.0f) - ((count * cicleSpace) / 2.0f);
        }

        float dX;
        float dY;

        float pageFillRadius = mRadius;

        //Draw stroked circles
        for (int iLoop = 0; iLoop < count; iLoop++) {
            float drawLong = longOffset + (iLoop * cicleSpace);
            if (mOrientation == HORIZONTAL) {
                dX = drawLong;
                dY = shortOffset;
            } else {
                dX = shortOffset;
                dY = drawLong;
            }
            // Only paint fill if not completely transparent
                canvas.drawCircle(dX, dY, mRadius, mPaintStroke);
        }

        //Draw the filled circle according to the current scroll
        float cx = (mSnap ? mSnapPage : mCurrentPage) * cicleSpace;
        if (!mSnap) {
            cx += mPageOffset * cicleSpace;
        }
        if (mOrientation == HORIZONTAL) {
            dX = longOffset + cx;
            dY = shortOffset;
        } else {
            dX = shortOffset;
            dY = longOffset + cx;
        }
        canvas.drawCircle(dX, dY, mRadius, mPaintFill);
    }

    public void setViewPager(ViewPager view) {
        if (mViewPager == view) {
            return;
        }
        if (mViewPager != null) {
            mViewPager.setOnPageChangeListener(null);
        }
        if (view.getAdapter() == null) {
            throw new IllegalStateException("ViewPager does not have adapter instance.");
        }
        mViewPager = view;
        mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
		        if (mSnap || mScrollState == ViewPager.SCROLL_STATE_IDLE) {
		            mCurrentPage = position;
		            mSnapPage = position;
		            invalidate();
		        }

		        if (mListener != null) {
		            mListener.onPageSelected(position);
		        }
		    }

			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
				mCurrentPage = position;
		        mPageOffset = positionOffset;
		        invalidate();

		        if (mListener != null) {
		            mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
		        }
			}

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

			        if (mListener != null) {
			            mListener.onPageScrollStateChanged(state);
			        }
			}
		});
        invalidate();
    }

    public void setViewPager(ViewPager view, int initialPosition) {
        setViewPager(view);
        setCurrentItem(initialPosition);
    }

    public void setCurrentItem(int item) {
        if (mViewPager == null) {
            throw new IllegalStateException("ViewPager has not been bound.");
        }
        mViewPager.setCurrentItem(item);
        mCurrentPage = item;
        invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mOrientation == HORIZONTAL) {
            setMeasuredDimension(measureLong(widthMeasureSpec), measureShort(heightMeasureSpec));
        } else {
            setMeasuredDimension(measureShort(widthMeasureSpec), measureLong(heightMeasureSpec));
        }
    }

    /**
     * Determines the width of this view
     *
     * @param measureSpec
     *            A measureSpec packed into an int
     * @return The width of the view, honoring constraints from measureSpec
     */
    private int measureLong(int measureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if ((specMode == MeasureSpec.EXACTLY) || (mViewPager == null)) {
            //We were told how big to be
            result = specSize;
        } else {
            //Calculate the width according the views count
            final int count = mViewPager.getAdapter().getCount();
            result = (int)(getPaddingLeft() + getPaddingRight()
                    + (count * 2 * mRadius) + (count - 1) * mRadius + 1);
            //Respect AT_MOST value if that was what is called for by measureSpec
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    /**
     * Determines the height of this view
     *
     * @param measureSpec
     *            A measureSpec packed into an int
     * @return The height of the view, honoring constraints from measureSpec
     */
    private int measureShort(int measureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            //We were told how big to be
            result = specSize;
        } else {
            //Measure the height
            result = (int)(2 * mRadius + getPaddingTop() + getPaddingBottom() + 1);
            //Respect AT_MOST value if that was what is called for by measureSpec
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState savedState = (SavedState)state;
        super.onRestoreInstanceState(savedState.getSuperState());
        mCurrentPage = savedState.currentPage;
        mSnapPage = savedState.currentPage;
        requestLayout();
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState savedState = new SavedState(superState);
        savedState.currentPage = mCurrentPage;
        return savedState;
    }

    static class SavedState extends BaseSavedState {
        int currentPage;

        public SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            currentPage = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeInt(currentPage);
        }

        @SuppressWarnings("UnusedDeclaration")
        public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

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

}

代码有点长啊,不过只是复制粘贴,应该没什么问题吧

  • 第三部,在含有viewpager的activity,引用如下几句代码,即可加上viewpagerindicator了
private CircleIndicatorHelper mIndicatorHelper = new CircleIndicatorHelper(this);
		mIndicatorHelper.setViewpager(mViewPager);

好了,就是这么的简单,这么的任性,从此再也不用担心加小圆圈了,不过问题来了,怎么自定义呢,我要的圆圈的颜色,大小,间距,OK,这些都是一句代码搞定;

mIndicatorHelper.setFillColor("#651717");
		mIndicatorHelper.setDefaultColor("#00A2E8");
		mIndicatorHelper.setRadius(8);

设置填充颜色,设置默认颜色,设置大小,简单便捷

好了,最后,别忘了,把viewpager的parent View设置成FrameLayout噢

时间: 2024-11-07 13:29:23

Android开发:史上最简单方便的viewpager加indicator的方法的相关文章

Android之——史上最简单最酷炫的3D图片浏览效果的实现

转载请注明出处:http://blog.csdn.net/l1028386804/article/details/48052709 如今,Android开发已经成为移动互联开发领域中一支不可或缺的力量,那么Android中要实现3D的效果那也就是合情合理的事情了.那么,如何在Android中实现像IOS中那样的3D图片浏览效果呢?下面,鄙人将重磅推出今天的重点博文,和大家一起在Android中实现酷炫的3D图片浏览效果. 一.原理 老规矩,还是要来啰嗦下原理的东西. 整体实现是以手机屏幕的正中间

Android之——史上最简单图片轮播广告效果实现

转载请注明出处:http://blog.csdn.net/l1028386804/article/details/48049913 如今的Android开发需求越来越来多,实现效果越来越酷炫,很多Android APP都要实现PC网站上那样的图片轮播效果,那么,这些图片的轮播效果是如何实现的呢?下面,我就跟大家一起来实现这些酷炫的功能. 一.原理 首先,将这些要轮播的图片和一些文本分别放置在不同的数据集合中,程序启动的时候默认显示一组图片和文本数据,然后启动一个定时器,每隔一段时间便替换掉显示的

Android之——史上最简单自定义开关按钮的实现

转载请注明出处:http://blog.csdn.net/l1028386804/article/details/48102871 很多时候,我们在很多无论是Android还是IOS的APP中都会遇到这样的一种效果,有一个按钮,我们点击一下,便会滑动一下,一会显示"开",一会显示"关",这便是开关按钮了,比如:很多Android手机的设置功能里,就有很多功能是用开关按钮实现的,那么这些开关按钮时如何实现的呢?下面,就让我们一起来实现这个功能吧. 一.原理 我们在界面

Android之——史上最简单旋转菜单实现效果

转载请注明出处:http://blog.csdn.net/l1028386804/article/details/48048323 由于身体原因,前几天没有给大家更新博客,那么,今天我们就来一起实现一个非常酷炫的旋转菜单效果吧.在很多APP中,不难发现,人家把菜单效果设计的那叫一个酷炫啊,其中一种设计就是将菜单设计成旋转的效果.好了,那么这么酷炫的菜单效果是如何实现的呢?下面,就让我们一起来实现这个酷炫的菜单效果吧. 一.原理 老规矩,还是先唠叨下原理级别的东西. 这个示例的实现原理很简单,利用

【Android】史上最简单,一步集成侧滑(删除)菜单,高仿QQ、IOS

本篇文章已授权微信公众号 guolin_blog (郭霖)独家发布 转载请标明出处: http://blog.csdn.net/zxt0601/article/details/53157090 本文出自:[张旭童的博客](http://blog.csdn.net/zxt0601) 代码传送门:喜欢的话,随手点个star.多谢 https://github.com/mcxtzhang/SwipeDelMenuLayout 重要的话 开头说,not for the RecyclerView or L

iOS史上最简单修改导航栏分隔线颜色方法!!!

override func viewDidLoad() { super.viewDidLoad() if let imageView = self.findNavLineView(view: navigationBar) { // 在分隔线上添加一个跟分隔线大小一模一样的View, 然后修改颜色即可 let navBarLineView = UIView() navBarLineView.frame = imageView.bounds navBarLineView.backgroundColo

史上最简单的个人移动APP开发入门--jQuery Mobile版跨平台APP开发

书是人类进步的阶梯. ——高尔基 习大大要求新新人类要有中国梦,鼓励大学生们一毕业就创业.那最好的创业途径是什么呢?就是APP.<构建跨平台APP-jQuery Mobile移动应用实战>就是一本写给没钱没身份没资历的创业小白看的APP书,看完这本书你可以拥有自己的一个APP,不用花钱就能移植到其他移动平台,支持iOS,Android,Windows Phone!!!!!!!!找个最便宜的来练手吧!  小白APP交流Q群:  348632872 清华大学出版社推出的<构建跨平台APP:j

开源框架】Android之史上最全最简单最有用的第三方开源库收集整理,有助于快速开发

[原][开源框架]Android之史上最全最简单最有用的第三方开源库收集整理,有助于快速开发,欢迎各位... 时间 2015-01-05 10:08:18 我是程序猿,我为自己代言 原文  http://blog.csdn.net/caoyouxing/article/details/42418591 主题 开源 安卓开发 http://www.tuicool.com/articles/jyA3MrU Android开源库 自己一直很喜欢Android开发,就如博客签名一样, 我是程序猿,我为自

Android 自定义控件打造史上最简单的侧滑菜单

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/39185641 ,本文出自[张鸿洋的博客] 侧滑菜单在很多应用中都会见到,最近QQ5.0侧滑还玩了点花样~~对于侧滑菜单,一般大家都会自定义ViewGroup,然后隐藏菜单栏,当手指滑动时,通过Scroller或者不断的改变leftMargin等实现:多少都有点复杂,完成以后还需要对滑动冲突等进行处理~~今天给大家带来一个简单的实现,史上最简单有点夸张,但是的确是我目前遇到过的最