package com.gh.gamecenter.common.view

import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import com.gh.gamecenter.common.utils.tryCatchInRelease

/**
 * 游戏列表标签的容器(特定功能的View)
 *
 * 一行内,防止标签显示越界
 */
class GameTagContainerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
    LinearLayout(context, attrs) {
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        tryCatchInRelease {
            var childContentWidth = 0
            for (i in 0 until childCount) {
                val tag = getChildAt(i)
                val tagLp = tag.layoutParams
                if (tagLp is LayoutParams) {
                    tag.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
                    val tagWidth = tagLp.leftMargin + tagLp.rightMargin + tag.measuredWidth
                    childContentWidth += tagWidth
                }
            }
            if (childContentWidth > width && childCount > 1) {
                removeViewAt(childCount - 1)
            }
        }
    }
}