为ViewPager设置CirclePageIndicator(小圆点)

系统 1652 0
一切为了快速迭代!

    
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.lang.reflect.Field;

/**
 * Created by liangfei on 3/26/15.
 */
public class CirclePageIndicator extends LinearLayout implements ViewPager.OnPageChangeListener {
    public static final int INDICATOR_TYPE_CIRCLE = 0;
    public static final int INDICATOR_TYPE_FRACTION = 1;

    public enum IndicatorType {
        CIRCLE(INDICATOR_TYPE_CIRCLE),
        FRACTION(INDICATOR_TYPE_FRACTION),
        UNKNOWN(-1);

        private int type;
        IndicatorType(int type) {
            this.type = type;
        }

        public static IndicatorType of(int value) {
            switch (value) {
                case INDICATOR_TYPE_CIRCLE:
                    return CIRCLE;
                case INDICATOR_TYPE_FRACTION:
                    return FRACTION;
                default:
                    return UNKNOWN;
            }
        }
    }

    public static final int DEFAULT_INDICATOR_SPACING = 5;

    private int mActivePosition = -1;
    private int mIndicatorSpacing;
    private boolean mIndicatorTypeChanged = false;

    private IndicatorType mIndicatorType = IndicatorType.of(INDICATOR_TYPE_CIRCLE);
    private ViewPager mViewPager;

    private ViewPager.OnPageChangeListener mUserDefinedPageChangeListener;

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

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

    public CirclePageIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs, R.styleable.CirclePageIndicator, 0, 0);
        try {
            mIndicatorSpacing = a.getDimensionPixelSize(
                    R.styleable.CirclePageIndicator_indicator_spacing,
                    DEFAULT_INDICATOR_SPACING);
            int indicatorTypeValue = a.getInt(
                    R.styleable.CirclePageIndicator_indicator_type,
                    mIndicatorType.type);
            mIndicatorType = IndicatorType.of(indicatorTypeValue);
        } finally {
            a.recycle();
        }

        init();
    }

    private void init() {
        setOrientation(HORIZONTAL);
        if (!(getLayoutParams() instanceof FrameLayout.LayoutParams)) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            params.gravity = Gravity.BOTTOM | Gravity.START;
            setLayoutParams(params);
        }
    }

    public void setViewPager(ViewPager pager) {
        mViewPager = pager;
        mUserDefinedPageChangeListener = getOnPageChangeListener(pager);
        pager.setOnPageChangeListener(this);
        setIndicatorType(mIndicatorType);
    }

    public void setIndicatorType(IndicatorType indicatorType) {
        mIndicatorType = indicatorType;
        mIndicatorTypeChanged = true;
        if (mViewPager != null) {
            addIndicator(mViewPager.getAdapter().getCount());
        }
    }

    private void removeIndicator() {
        removeAllViews();
    }

    private void addIndicator(int count) {
        removeIndicator();
        if (count <= 0) return;
        if (mIndicatorType == IndicatorType.CIRCLE) {
            for (int i = 0; i < count; i++) {
                ImageView img = new ImageView(getContext());
                LayoutParams params = new LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                params.leftMargin = mIndicatorSpacing;
                params.rightMargin = mIndicatorSpacing;
                img.setImageResource(R.drawable.circle_indicator_stroke);
                addView(img, params);
            }
        } else if (mIndicatorType == IndicatorType.FRACTION) {
            TextView textView = new TextView(getContext());
            textView.setTag(count);
            LayoutParams params = new LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            addView(textView, params);
        }
        updateIndicator(mViewPager.getCurrentItem());
    }

    private void updateIndicator(int position) {
        if (mIndicatorTypeChanged || mActivePosition != position) {
            mIndicatorTypeChanged = false;
            if (mIndicatorType == IndicatorType.CIRCLE) {
                ((ImageView) getChildAt(mActivePosition))
                        .setImageResource(R.drawable.circle_indicator_stroke);
                ((ImageView) getChildAt(position))
                        .setImageResource(R.drawable.circle_indicator_solid);
            } else if (mIndicatorType == IndicatorType.FRACTION) {
                TextView textView = (TextView) getChildAt(0);
                //noinspection RedundantCast
                textView.setText(String.format("%d/%d", position + 1, (int) textView.getTag()));
            }
            mActivePosition = position;
        }
    }

    private ViewPager.OnPageChangeListener getOnPageChangeListener(ViewPager pager) {
        try {
            Field f = pager.getClass().getDeclaredField("mOnPageChangeListener");
            f.setAccessible(true);
            return (ViewPager.OnPageChangeListener) f.get(pager);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        if (mUserDefinedPageChangeListener != null) {
            mUserDefinedPageChangeListener.onPageScrolled(position, positionOffset,
                    positionOffsetPixels);
        }
    }

    @Override
    public void onPageSelected(int position) {
        updateIndicator(position);
        if (mUserDefinedPageChangeListener != null) {
            mUserDefinedPageChangeListener.onPageSelected(position);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (mUserDefinedPageChangeListener != null) {
            mUserDefinedPageChangeListener.onPageScrollStateChanged(state);
        }
    }
}


  


自定义属性:
    
<resources>
    <declare-styleable name="CirclePageIndicator">
        <attr name="indicator_spacing" format="dimension" />
        <attr name="indicator_type" format="enum">
            <enum name="circle" value="0" />
            <enum name="fraction" value="1" />
        </attr>
    </declare-styleable>
</resources>

  


两个点:







不使用上面的类。
快速的使用方法:
伪代码
    

private ViewPager viewPager;
	private LinearLayout indicators;
	private ArrayList<View> listViews = new ArrayList<View>();
	private int curPagerPosition=0,oldPagerPosition=0;
.......
viewPager=(ViewPager)findViewById(R.id.viewPager);
indicators=(LinearLayout)findViewById(R.id.indicators);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				// TODO Auto-generated method stub
				indicators.getChildAt(oldPagerPosition).setBackgroundResource(R.drawable.img_detail_dot_normal);
				indicators.getChildAt(position).setBackgroundResource(R.drawable.img_detail_dot_selected);
				oldPagerPosition=position;
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});

  


    
indicators.removeAllViews();
LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.leftMargin=10;
params.rightMargin=10;
List<ProductImgEntity> imgs=curProductDetailInfo.getImgs();
						if(curProductDetailInfo.getImgs()==null){
							showToast(R.string.alert_data_incomplete);
	return;
}
						int size=imgs.size();
						for(int i=0;i<size;i++){
							View view=LayoutInflater.from(context).inflate(R.layout.item_product_img, null);
							ImageView item_0=(ImageView)view.findViewById(R.id.item_0);
							Commands.loadImageByVolley(curProductDetailInfo.getImgs().get(i).getImgUrl(),item_0,R.drawable.default_img,400,400);
							listViews.add(view);
							
							ImageView child=new ImageView(context);
							child.setLayoutParams(params);
							child.setBackgroundResource(i==curPagerPosition?R.drawable.img_detail_dot_selected:R.drawable.img_detail_dot_normal);
							indicators.addView(child);
						}
						
						viewPager.setAdapter(new MyPagerAdapter(listViews));

  







为ViewPager设置CirclePageIndicator(小圆点)


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论