package xn.hxp.weidith import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.view.View class PageIndicatorView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private var currentPage = 0 private var totalPages = 1 private val activePaint: Paint private val inactivePaint: Paint init { activePaint = Paint().apply { color = Color.BLUE style = Paint.Style.FILL } inactivePaint = Paint().apply { color = Color.GRAY style = Paint.Style.FILL } } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val width = width val height = height val radius = height / 4 val gap = height / 2 val totalWidth = (totalPages - 1) * gap + 2 * radius * totalPages val startX = (width - totalWidth) / 2 for (i in 0 until totalPages) { val paint = if (i == currentPage) activePaint else inactivePaint canvas.drawCircle(startX + i * (2 * radius + gap) + radius.toFloat(), height / 2.toFloat(), radius.toFloat(), paint) } } fun setCurrentPage(currentPage: Int) { this.currentPage = currentPage invalidate() } fun setTotalPages(totalPages: Int) { this.totalPages = totalPages invalidate() } }