2

I want to have Toolbar title gravity start|center_vertical Expected result : expected

But actual result is : actual Steps to reproduce:

  • I'm creating View class and extending MaterialToolbar

    class AppBarSample @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : MaterialToolbar(context, attrs, defStyleAttr) {

     private var iconType: IconType? = null
    
     init {
         context.theme.obtainStyledAttributes(
             attrs,
             R.styleable.AppBarSample,
             defStyleAttr,
             R.style.Sample_Theme_App_AppBar
         ).apply {
             try {
                 iconType =
                     getEnum(
                         R.styleable.AppBarSample_navIcon,
                         IconType.BACK
                     )
             } finally {
                 recycle()
             }
         }
         setNavIcon()
     }
    
     private fun setNavIcon() {
         iconType?.apply {
             navigationIcon = when (this) {
                 IconType.BACK -> ContextCompat.getDrawable(context, R.drawable.ic_action_name)
                 IconType.CLOSE -> ContextCompat.getDrawable(context, R.drawable.ic_close)
             }
         }
     }
    
     enum class IconType {
         BACK, CLOSE
     }
    
     private inline fun <reified T : Enum<T>> TypedArray.getEnum(index: Int, default: T) =
         getInt(index, -1).let {
             if (it >= 0) enumValues<T>()[it] else default
         }
    

    }

  • My theme file

        <resources xmlns:tools="http://schemas.android.com/tools">
     <!-- Base application theme. -->
     <style name="Theme.MaterialUISample" parent="Theme.MaterialComponents.DayNight.NoActionBar.Bridge">
        ...
     </style>
    
     <style name="Sample.Theme.App" parent="Theme.Material3.Dark.NoActionBar">
         <item name="actionBarTheme">@style/ThemeOverlay.Material3.Dark.ActionBar</item>
     </style>
    
     <style name="Sample.Theme.App.AppBar" parent="Widget.Material3.Toolbar">
         <item name="navigationIcon">@null</item>
         <item name="android:fitsSystemWindows">true</item>
         <item name="titleTextAppearance">@style/TextAppearance.Material3.ActionBar.Title</item>
     </style>
    
  • setting android:theme from xml

        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:theme="@style/Sample.Theme.App.AppBar"
        app:title="Post"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    
    
    

P.S I don't want to use app:titleMarginTop="".

lika
  • 21
  • 3

1 Answers1

0

Add this line in your layout.

  app:titleCentered="true"