Android如何自定义圆点指示器
创始人
2024-12-17 13:22:08
0次

先上效果图

Android如何自定义圆点指示器

大概思路就是自定义View 从左至右绘制圆点 然后在ViewPager的OnPageChangeListener中设置当前页面的圆点

下面是代码

先定义属性


    
    
    
        
        
    

接下来是自定义的View

public class Indicator extends View{
 
    private static final int DEFAULT_TOTAL_INDEX = 5;
    private static final int DEFAULT_CURRENT_INDEX = 0;
    private static final int DEFAULT_CIRCLE_DISTANCE = 40;
    private static final int DEFAULT_CIRCLE_RADIUS = 8;
    private static final int DEFAULT_CIRCLE_SELECTED_RADIUS = 11;
 
    private int selectedColor;
    private int unselectedColor;
    private int currentIndex;
    private int totalIndex;
    private Paint paint;
    private int startX;
    private int startSelectedY;
    private int startY;
    private int centreX;
 
    public Indicator(Context context) {
        this(context,null);
    }
 
    public Indicator(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }
 
    public Indicator(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs,R.styleable.Indicator,defStyleAttr,0);
        selectedColor = typedArray.getColor(R.styleable.Indicator_selectedColor, Color.LTGRAY);
        unselectedColor = typedArray.getColor(R.styleable.Indicator_unselectedColor,Color.WHITE);
        typedArray.recycle();
        totalIndex = DEFAULT_TOTAL_INDEX;
        currentIndex = DEFAULT_CURRENT_INDEX;
        paint = new Paint();
    }

从TypedArray中获取自定义的属性,totalIndex是总的圆点个数,currentIndex是当前页面的圆点
接下来是重写的OnDraw()方法

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        centreX = getWidth() / 2;
        startSelectedY = getHeight() / 2 - DEFAULT_CIRCLE_SELECTED_RADIUS;
        startY = getHeight() / 2 - DEFAULT_CIRCLE_RADIUS;
        if (totalIndex % 2 == 0){
            startX = centreX - (int)(1.0 * (totalIndex - 1)/2 * DEFAULT_CIRCLE_DISTANCE);
        }else{
            startX = centreX - totalIndex / 2 * DEFAULT_CIRCLE_DISTANCE;
        }
        paint.setAntiAlias(true);
        paint.setColor(unselectedColor);
        int tempX = startX;
        for(int i = 0 ; i < totalIndex ; i++ ){
            RectF rectF = new RectF(tempX - DEFAULT_CIRCLE_RADIUS,startY,
                    tempX + DEFAULT_CIRCLE_RADIUS,startY + 2 * DEFAULT_CIRCLE_RADIUS);
            if (i == currentIndex) {
                paint.setColor(selectedColor);
                rectF = new RectF(tempX - DEFAULT_CIRCLE_SELECTED_RADIUS,startSelectedY,
                        tempX + DEFAULT_CIRCLE_SELECTED_RADIUS,startSelectedY + 2 * DEFAULT_CIRCLE_SELECTED_RADIUS);
            }
            canvas.drawOval(rectF,paint);
            if (paint.getColor() == selectedColor)
                paint.setColor(unselectedColor);
            tempX += DEFAULT_CIRCLE_DISTANCE;
        }
    }

因为当前页面的圆点和未选中页面的圆点要设置不同的大小 所以分别设置每个圆点的坐标 然后用for循环绘制圆点
这里有一点要注意 new RectF() 的四个参数分别是圆点外面的矩形的左上角的X,Y和右下角的X,Y

接下来是设置当前页面的圆点的方法

public void setCurrentIndex(int currentIndex){
        //if (currentIndex < 0)
        //    currentIndex += totalIndex ;
        //if (currentIndex > totalIndex - 1)
        //    currentIndex %= totalIndex;
        this.currentIndex = currentIndex;
        invalidate();
    }

注释里的代码是当页面可以循环的时候设置的
接下来是设置总的圆点个数的方法

public void setTotalIndex(int totalIndex){
        int oldTotalIndex = this.totalIndex;
        if (totalIndex < 1)
            return;
        if (totalIndex < oldTotalIndex){
            if (currentIndex == totalIndex )
                currentIndex = totalIndex - 1;
        }
        this.totalIndex = totalIndex;
        invalidate();
    }

当删除圆点的时候 如果currentIndex是最后一个 让currentIndex向前移动
接下来是重写的OnMeasure()方法

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec));
    }
 
    private int measureHeight(int measureSpec){
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        int desired = DEFAULT_CIRCLE_SELECTED_RADIUS * 2 + getPaddingBottom() + getPaddingTop();
        if(specMode == MeasureSpec.EXACTLY) {
            result = Math.max(desired,specSize);
        }else{
            if(specMode == MeasureSpec.AT_MOST){
                result = Math.min(desired,specSize);
            }
            else result = desired;
        }
        return result;
    }
 
    private int measureWidth(int measureSpec){
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        int desired = (totalIndex - 1) * DEFAULT_CIRCLE_DISTANCE + DEFAULT_CIRCLE_SELECTED_RADIUS * 2 + getPaddingLeft() + getPaddingRight();
        if(specMode == MeasureSpec.EXACTLY) {
            result = Math.max(desired,specSize);
        }else{
            if(specMode == MeasureSpec.AT_MOST){
                result = Math.min(desired,specSize);
            }else result = desired;
        }
        return result;
    }

下面是MainActivity的布局代码,很简单


 
    
 
    
 

下面是MainActivity的代码

public class MainActivity extends AppCompatActivity {
 
    View layout1,layout2,layout3;
    ViewPager viewPager;
    Indicator indicator;
 
    List viewList;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        LayoutInflater inflater = getLayoutInflater();
        layout1 = inflater.inflate(R.layout.layout1,null);
        layout2 = inflater.inflate(R.layout.layout2,null);
        layout3 = inflater.inflate(R.layout.layout3,null);
 
        viewList = new ArrayList<>();
        viewList.add(layout1);
        viewList.add(layout2);
        viewList.add(layout3);
 
 
        indicator = (Indicator) findViewById(R.id.indicator);
        indicator.setTotalIndex(viewList.size());
        PagerAdapter pagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return viewList.size();
            }
 
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(viewList.get(position));
            }
 
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(viewList.get(position));
 
                return position;
            }
 
            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == viewList.get(Integer.parseInt(object.toString()));
            }
        };
 
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOnPageChangeListener(new PageChangeListener());
 
    }
 
    public class PageChangeListener implements ViewPager.OnPageChangeListener{
 
 
        @Override
        public void onPageSelected(int position) {
 
            indicator.setCurrentIndex(position);
        }
 
        @Override
        public void onPageScrollStateChanged(int state) {
 
        }
 
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
 
        }
    }

ViewPager里添加了三个空页面 然后设置指示器的圆点个数,最后在ViewPager的OnPageChangeListener中设置当前的 页面的圆点。

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...