package com.example.base.widget

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.Gravity
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.core.view.children


/**
 * 自定义标题栏 实现标题居中
 */
class TitleBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : Toolbar(context, attrs, defStyleAttr) {

    var titleView: TextView

    init {

        // 居中导航键
        val navImageButton = children.find { it is ImageButton } as ImageButton
        (navImageButton.layoutParams as LayoutParams).gravity = Gravity.CENTER_VERTICAL

        // 标题居中
        titleView = children.find { it is TextView } as TextView
        val layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        layoutParams.gravity = Gravity.CENTER
        titleView.layoutParams = layoutParams

        setBackgroundColor(Color.TRANSPARENT)
        setTitleTextColor(Color.parseColor("#212226"))
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        titleView.x = ((width - titleView.width) / 2).toFloat()
    }

}