Saya menghabiskan beberapa hari mencari solusi universal. Toolbar saya bekerja dengan menu android dan ikon nav.
Pada awalnya, Anda perlu membuat kelas toolbar kustom. Kelas ini harus memiliki posisi menghitung posisi tengah (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<TextView>(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)
}
Kedua, Anda perlu membuat toolbar layout:
<CenteredToolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar">
<TextView
android:id="@+id/centerTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</CenteredToolbar>
Itu saja