//设置左侧图标之后在调用
fun Toolbar.setTitleCenter(text: String, sub: String? = null) {
//设置标题
title = text;subtitle = sub
var titleWidth = 0
//完全是心理暗示 正常是标题先初始化 然后是副标题
var subView: TextView? = null
forEach { view ->
if (view is ImageButton && navigationIcon == view.drawable) {
//如果左边有图标就将titleMarginStart减少 通过打印发现左边有图标的时候titleMarginStart初始化就位10 所以这里减掉
view.post { titleMarginStart -= view.width + 10 }
} else if (view is TextView && text == view.text) {
view.post {
titleWidth = view.width
subView?.setParams(width = titleWidth)
//屏幕宽度的一般减去title的宽度的一般 就是 titleMarginStart
titleMarginStart += ScreenUtils.getScreenWidth() / 2 - view.width / 2
}
} else if (view is TextView && sub == view.text) {
//副标题内容居中
view.gravity = Gravity.CENTER
view.post {
//设置副标题和主标题一样宽
if (titleWidth == 0) subView = view else view.setParams(width = titleWidth)
}
}
}
}
fun View.setParams(width: Int? = null, height: Int? = null) {
val params = layoutParams
if (width != null) params.width = width
if (height != null) params.height = height
layoutParams = params
}
网友评论