youth5201314 / banner

🔥🔥🔥Banner 2.0 来了!Android广告图片轮播控件,内部基于ViewPager2实现,Indicator和UI都可以自定义。
Apache License 2.0
12.92k stars 2.52k forks source link

教你如何给指示器indicator设置点击事件onclick,同步banner一起滚动,kotlin代码 #1080

Closed SelectSex closed 10 months ago

SelectSex commented 3 years ago

 bindView.indicator.setOnTouchListener(View.OnTouchListener { v, event ->
            (v as? BaseIndicator)?.let { view: BaseIndicator ->
                val config = view.indicatorConfig
                if (config.indicatorSize > 1) {
                    if (event.action == MotionEvent.ACTION_DOWN || event.action == MotionEvent.ACTION_UP) {
                        val eventX = event.rawX.toInt()
                        val eventY = event.rawY.toInt()
                        val rect = Rect()
                        view.getGlobalVisibleRect(rect)

                        if (event.action == MotionEvent.ACTION_UP) {
                            val leftOld = rect.left
                            var left = leftOld
                            var right = leftOld
                            val spaceHalf: Int = config.indicatorSpace shr 1
                            for (i in 0 until config.indicatorSize) {
                                val indicatorWidth: Int = if (config.currentPosition == i) config.selectedWidth else config.normalWidth

                                when (i) {
                                    0 -> {
                                        left = leftOld
                                        right = left + indicatorWidth + spaceHalf
                                    }
                                    else -> {
                                        left = right
                                        right += config.indicatorSpace + indicatorWidth
                                    }
                                }
                                rect.set(left, rect.top, right, rect.bottom)
                                if (rect.contains(eventX, eventY)) {
                                    //必须加1也不知道为啥
                                    bindView.bannerHome.currentItem = i + 1
                                    return@OnTouchListener true
                                }
                            }
                        }
                        return@OnTouchListener true
                    }
                }
            }
            return@OnTouchListener false
        })