自定义Android圆点指示器

先上效果图


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

下面是代码

先定义属性

<resources>
    <attr name="selectedColor" format="color"/>
    <attr name="unselectedColor" format="color"/>
    <declare-styleable name="Indicator">
        <attr name="selectedColor"/>
        <attr name="unselectedColor"/>
    </declare-styleable>
</resources>

接下来是自定义的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的布局代码,很简单

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.lzh123.learnviewpager.MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <com.example.lzh123.learnviewpager.Indicator
        app:selectedColor="#FFFFFF"
        app:unselectedColor="#C7C7C7"
        android:id="@+id/indicator"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
下面是MainActivity的代码

public class MainActivity extends AppCompatActivity {

    View layout1,layout2,layout3;
    ViewPager viewPager;
    Indicator indicator;

    List<View> 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中设置当前的 页面的圆点。


以上




  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 圆点指示器常用于 ViewPager、RecyclerView 等控件的指示,用于表示当前显示页面的位置。一般来说,可以通过自定义 View 或者使用第三方库来实现圆点指示器。 以下是使用自定义 View 实现圆点指示器的基本步骤: 1. 创建一个自定义 View 类,继承自 View。 2. 在自定义 View 的构造函数中初始化相关参数,如圆点的颜色、大小、间距等。 3. 重写 onMeasure 方法,设置自定义 View 的大小。 4. 重写 onDraw 方法,在画布上绘制圆点。 5. 在需要使用圆点指示器的地方,将自定义 View 添加到布局中即可。 以下是一个简单的圆点指示器示例代码: ```java public class CircleIndicatorView extends View { private static final int DEFAULT_COLOR = Color.WHITE; private static final int DEFAULT_RADIUS = 10; private static final int DEFAULT_SPACING = 20; private int mCircleColor = DEFAULT_COLOR; private int mCircleRadius = DEFAULT_RADIUS; private int mCircleSpacing = DEFAULT_SPACING; private int mCount = 0; private int mCurrent = 0; public CircleIndicatorView(Context context) { super(context); } public CircleIndicatorView(Context context, AttributeSet attrs) { super(context, attrs); } public CircleIndicatorView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setCount(int count) { mCount = count; invalidate(); } public void setCurrent(int current) { mCurrent = current; invalidate(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = mCircleRadius * 2 * mCount + mCircleSpacing * (mCount - 1); int height = mCircleRadius * 2; setMeasuredDimension(width, height); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (int i = 0; i < mCount; i++) { int cx = mCircleRadius + (mCircleRadius * 2 + mCircleSpacing) * i; int cy = mCircleRadius; canvas.drawCircle(cx, cy, mCircleRadius, mCircleColor); if (i == mCurrent) { canvas.drawCircle(cx, cy, mCircleRadius - 5, DEFAULT_COLOR); } } } } ``` 在布局文件中引用该自定义 View: ```xml <com.example.CircleIndicatorView android:id="@+id/circle_indicator_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" app:circleColor="#FF0000" app:circleRadius="10dp" app:circleSpacing="20dp" /> ``` 注意,在自定义 View 中使用属性时需要在 attrs.xml 文件中定义对应的属性。 当然,还有很多第三方库可以实现圆点指示器,比如 ViewPagerIndicator、SmartTabLayout 等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值