PageIndicatorView.kt 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package xn.hxp.weidith
  2. import android.content.Context
  3. import android.graphics.Canvas
  4. import android.graphics.Color
  5. import android.graphics.Paint
  6. import android.util.AttributeSet
  7. import android.view.View
  8. class PageIndicatorView @JvmOverloads constructor(
  9. context: Context,
  10. attrs: AttributeSet? = null,
  11. defStyleAttr: Int = 0
  12. ) : View(context, attrs, defStyleAttr) {
  13. private var currentPage = 0
  14. private var totalPages = 1
  15. private val activePaint: Paint
  16. private val inactivePaint: Paint
  17. init {
  18. activePaint = Paint().apply {
  19. color = Color.BLUE
  20. style = Paint.Style.FILL
  21. }
  22. inactivePaint = Paint().apply {
  23. color = Color.GRAY
  24. style = Paint.Style.FILL
  25. }
  26. }
  27. override fun onDraw(canvas: Canvas) {
  28. super.onDraw(canvas)
  29. val width = width
  30. val height = height
  31. val radius = height / 4
  32. val gap = height / 2
  33. val totalWidth = (totalPages - 1) * gap + 2 * radius * totalPages
  34. val startX = (width - totalWidth) / 2
  35. for (i in 0 until totalPages) {
  36. val paint = if (i == currentPage) activePaint else inactivePaint
  37. canvas.drawCircle(startX + i * (2 * radius + gap) + radius.toFloat(), height / 2.toFloat(), radius.toFloat(), paint)
  38. }
  39. }
  40. fun setCurrentPage(currentPage: Int) {
  41. this.currentPage = currentPage
  42. invalidate()
  43. }
  44. fun setTotalPages(totalPages: Int) {
  45. this.totalPages = totalPages
  46. invalidate()
  47. }
  48. }