Android toolbar center title and custom font

前端 未结 30 3221
时光说笑
时光说笑 2020-11-22 04:11

I\'m trying to figure out the right way to use a custom font for the toolbar title, and center it in the toolbar (client requirement).

At the moment, i\'m using the

30条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 05:02

    I spent several days searching for a universal solution. My toolbar working with android menu and nav icon.

    At first, you need create custom toolbar class. This class must have calculate title centered positions (paddings):

        class CenteredToolbar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
        : Toolbar(context, attrs, defStyleAttr) {
    
        init {
            addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
                override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
                    val titleTextView = findViewById(R.id.centerTitle)
    
                    val x = titleTextView.x.toInt()
                    val x2 = x + titleTextView.width
    
                    val fullWidth = width
                    val fullCenter = fullWidth / 2
    
                    val offsetLeft = Math.abs(fullCenter - x)
                    val offsetRight = Math.abs(x2 - fullCenter)
                    val differOffset = Math.abs(offsetLeft - offsetRight)
    
                    if (offsetLeft > offsetRight) {
                        titleTextView.setPadding(differOffset, 0, 0, 0)
                    } else if (offsetRight > offsetLeft) {
                        titleTextView.setPadding(0, 0, differOffset, 0)
                    }
    
                    removeOnLayoutChangeListener(this)
                }
            })
        }
    
        override fun setTitle(resId: Int) = getTitleView().setText(resId)
    
        override fun setTitle(title: CharSequence?) = getTitleView().setText(title)
    
        fun getTitleView(): TextView = findViewById(R.id.centerTitle)
    
    }
    

    Secondly, you need create layout toolbar:

    
    
        
    
    
    

    That's all

提交回复
热议问题