Android: How to Center title in ToolBar

后端 未结 19 2002
执念已碎
执念已碎 2020-11-27 19:04

I am using ToolBar in my project first time, so i do not know how to customized the toolbar in android. I need to centered title in to the tool bar and how to do that please

19条回答
  •  庸人自扰
    2020-11-27 19:29

    Based on @LiuWenbin_NO,

    I had created a custom toolbar, which didn't need any extra view to center title in textview,

    import android.content.Context
    import android.util.AttributeSet
    import android.widget.TextView
    import androidx.appcompat.widget.Toolbar
    import android.view.Gravity
    
    class CenteredToolbar(context: Context, attrs: AttributeSet?, defStyleAttr: Int):
    Toolbar(context, attrs, defStyleAttr) {
    
    constructor(context: Context) : this(context, null, 0)
    
    constructor(context: Context, attrs: AttributeSet) : this(context, attrs, androidx.appcompat.R.attr.toolbarStyle)
    
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
    
        val childCount = childCount
        for (i in 0 until childCount) {
            val view = this.getChildAt(i)
            if (view is TextView) {
                forceTitleCenter(view,l, r)
                break
            }
        }
    }
    
    /**
     * Centering the layout.
     *
     * @param view The view to be centered
     */
    private fun forceTitleCenter(view: TextView, l: Int,  r: Int) {
        val top = view.getTop()
        val bottom = view.getBottom()
        view.layout(l, top, r, bottom)
        navigationIcon?.let{
            view.setPadding(it.intrinsicWidth,0,0,0)
        }
        view.gravity = Gravity.CENTER
    }
    

    }

     
    

提交回复
热议问题