溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android怎么實(shí)現(xiàn)循環(huán)輪播跑馬燈效果

發(fā)布時(shí)間:2023-05-04 15:33:18 來源:億速云 閱讀:91 作者:iii 欄目:開發(fā)技術(shù)

這篇“Android怎么實(shí)現(xiàn)循環(huán)輪播跑馬燈效果”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Android怎么實(shí)現(xiàn)循環(huán)輪播跑馬燈效果”文章吧。

支持暫停,恢復(fù),view自定義和池化回收復(fù)用。使用上,只需要引入xml,并綁定factory即可,內(nèi)部會(huì)在attach時(shí)自動(dòng)開始

 <MarqueeAnimalView
        android:id="@+id/marqueeView"
        android:layout_width="200dp"
        android:layout_height="30dp"
        android:background="@color/color_yellow" />
val list = mutableListOf("我是跑馬燈1", "我不是跑馬燈", "你猜我是不是跑馬燈")
var position = 0
view.marqueeView.setFactory(object : PoolViewFactory {
    override fun makeView(layoutInflater: LayoutInflater, parent: ViewGroup): View {
        val view = TextView(this@ViewActivity)
        view.setPadding(0, 0, 20.dp(), 0)
        view.textSize = 12f
        view.setTextColor(ResourceUtil.getColor(R.color.white))
        return view
    }
    override fun setAnimator(objectAnimator: ObjectAnimator, width: Int, parentWidth: Int) {
        objectAnimator.duration = (parentWidth + width) * 5L
    }
    override fun setView(view: View): Boolean {
        (view as? TextView)?.text = list[position++ % list.size]
        return true
    }
})

池化思路

參考Message的思路,對(duì)view進(jìn)行回收復(fù)用,避免內(nèi)存持續(xù)增長(zhǎng),增大GC壓力

private fun obtain(): View? {
    synchronized(sPoolSync) {
        if (!isAttachedToWindow) {
            return null
        }
        if (queue.isNotEmpty()) {
            return queue.poll()
        }
    }
    return factory?.makeView(layoutInflater, this@MarqueeAnimalView)?.apply {
        addView(this, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
    }
}
private fun recycle(view: View) {
    synchronized(sPoolSync) {
        if (queue.size < MAX_POOL_SIZE) {
            queue.offer(view)
        }
    }
}

創(chuàng)造工廠

這里的思路源于ViewSwitchFactory

interface PoolViewFactory {
    fun makeView(layoutInflater: LayoutInflater, parent: ViewGroup): View
    fun setAnimator(objectAnimator: ObjectAnimator, width: Int, parentWidth: Int)
    /**
     * 返回值,代表view是否需要重新測(cè)量
     */
    fun setView(view: View): Boolean
}

輪詢切換

這里根據(jù)對(duì)動(dòng)畫進(jìn)行初始化,并設(shè)置合適的監(jiān)聽。此時(shí)需要獲取當(dāng)view和parent的width,以用于標(biāo)定始末位置,需要注意x軸的正負(fù)方向。animators用于存儲(chǔ)開始的動(dòng)畫,這也是設(shè)計(jì)時(shí)存在的遺留問題,因?yàn)橹鲃?dòng)取消所有動(dòng)畫,但view->animator是單向綁定關(guān)系,所以需要保存發(fā)生的動(dòng)畫

private val animators = hashMapOf<String, ObjectAnimator>()
private fun next(view: View?) {
    view ?: return
    if (factory?.setView(view) == true) {
        view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
    }
    val width = view.measuredWidth
    val parentWidth = measuredWidth
    val targetValue = parentWidth - width
    val animator = ObjectAnimator.ofFloat(view, PROPERTY_NAME, parentWidth.toFloat(), -width.toFloat()).apply {
        // null即為默認(rèn)線性插值器
        interpolator = null
        addUpdateListener(
            RecyclerAnimatorUpdateListener(targetValue) {
                next(obtain())
                removeUpdateListener(it)
            }
        )
        addListener(this@MarqueeAnimalView)
        factory?.setAnimator(this, width, parentWidth)
    }
    animators["${view.hashCode()}-${animator.hashCode()}"] = animator
    animator.start()
}

動(dòng)畫監(jiān)聽

當(dāng)動(dòng)畫結(jié)束時(shí),需要對(duì)view進(jìn)行回收,并對(duì)動(dòng)畫移除。取消動(dòng)畫時(shí),需要將view強(qiáng)制歸位

同時(shí),為了方便使用,OnAttachStateChangeListener使得整體動(dòng)畫更加平滑,也避免了view不可見時(shí),動(dòng)畫仍然在持續(xù)執(zhí)行浪費(fèi)資源。當(dāng)然如fragment不可見時(shí)的監(jiān)聽需要完善

override fun onAnimationEnd(animation: Animator?) {
    (animation as? ObjectAnimator)?.let { animator ->
        (animator.target as? View)?.let { view ->
            animators.remove("${view.hashCode()}-${animator.hashCode()}")
            recycle(view)
        }
        // target釋放
        animator.target = null
    }
}
override fun onAnimationCancel(animation: Animator?) {
    (animation as? ObjectAnimator)?.let { animator ->
        (animator.target as? View)?.let { view ->
            view.translationX = measuredWidth.toFloat()
        }
    }
}
override fun onViewAttachedToWindow(v: View?) {
    if (animators.isNotEmpty()) {
        resume()
    } else {
        start()
    }
}
override fun onViewDetachedFromWindow(v: View?) {
    pause()
}

對(duì)外能力

fun start() {
    if (measuredWidth == 0) {
        this.post {
            // 如果測(cè)量還未完成,那就等待post后發(fā)起
            next(obtain())
        }
        return
    }
    next(obtain())
}
fun stop() {
    val it = animators.values.iterator()
    while (it.hasNext()) {
        val i = it.next()
        it.remove()
        i.cancel()
    }
}
fun pause() {
    for (i in animators.values) {
        i.pause()
    }
}
fun resume() {
    for (i in animators.values) {
        i.resume()
    }
}

以上就是關(guān)于“Android怎么實(shí)現(xiàn)循環(huán)輪播跑馬燈效果”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI