티스토리 뷰

반응형
SMALL

 

반응형

 

심플하게 인디케이터를 사용해야 할 때 

class IndicatorDotView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
): LinearLayout(context, attrs, defStyleAttr) {

    private val dotList = mutableListOf<View>()

    init {
        orientation = LinearLayout.HORIZONTAL
    }

    fun withViewPager(viewPager: ViewPager2) {
        initDotView(viewPager.adapter?.itemCount ?: 0)
    }

    fun select(index: Int) {
        dotList.mapIndexed { i, view ->
            (view.background as? GradientDrawable)?.setColor(
                if (index == i) ContextCompat.getColor(context, R.color.color_111111)
                else ContextCompat.getColor(context, R.color.color_cfcfcf)
            )
        }
    }

    private fun initDotView(count: Int) {
        for (i in 0 until count) {
            val view = makeDotView()
            view.layoutParams = LayoutParams(6.toPx, 6.toPx).apply {
                if (i == 0) {
                    marginEnd = 3.toPx
                } else if (i == (count - 1)) {
                    marginStart = 3.toPx
                } else {
                    marginStart = 3.toPx
                    marginEnd = 3.toPx
                }
            }
            dotList.add(view)
            addView(view)
        }
    }

    private fun makeDotView(): View =
        View(context).apply {
            background = ContextCompat.getDrawable(context, R.drawable.shape_dot_indicator)
        }

}

 

 

반응형
LIST
댓글