Android: How to Center title in ToolBar

后端 未结 19 2035
执念已碎
执念已碎 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:53

    for kotlin users from @user2137020 answer:

    package com.example.safetyofficer.view
    
    import android.content.Context
    import android.util.AttributeSet
    import android.widget.TextView
    import androidx.appcompat.widget.Toolbar
    import com.example.safetyofficer.R
    
    
    class CustomToolbar @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = R.attr.toolbarStyle
    ) :
        Toolbar(context, attrs, defStyleAttr) {
        private val titleView: TextView = TextView(getContext())
    
        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()
        }
    
        override fun setTitle(title: CharSequence) {
            titleView.text = title
        }
    
        init {
            val textAppearanceStyleResId: Int
            val a = context.theme.obtainStyledAttributes(
                attrs,
                intArrayOf(R.attr.titleTextAppearance),
                defStyleAttr,
                0
            )
            textAppearanceStyleResId = try {
                a.getResourceId(0, 0)
            } finally {
                a.recycle()
            }
            if (textAppearanceStyleResId > 0) {
                titleView.setTextAppearance(textAppearanceStyleResId)
            }
            addView(titleView, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT))
        }
    }
    

提交回复
热议问题