Android - How to center a title (TextView) in a toolbar?

后端 未结 3 1682
悲&欢浪女
悲&欢浪女 2021-01-21 14:15

On the left of my toolbar I have a logo, and I want to center a TextView in the same toolbar to act as my title. For some reason, the title does not center, and is instead on th

相关标签:
3条回答
  • 2021-01-21 15:04

    If you give gravity as center then it should work. One more way is to setting width of your textview as match_parent and giving text_alignment as center

    0 讨论(0)
  • 2021-01-21 15:11
    <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize">
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="@string/title_activity_add_medication"
                android:textSize="16sp"
                android:textStyle="bold"
                android:textColor="@android:color/white"
                android:textAllCaps="true"
                android:layout_marginEnd="72dp"
                android:gravity="center"/>
    </android.support.v7.widget.Toolbar>
    
    0 讨论(0)
  • 2021-01-21 15:12

    There are a couple of ways to solve your problem. The quickest one would be to change your TextView as follows.

    <TextView
                android:id="@+id/toolbar_title"
                android:layout_width="match_parent" // Fill parent
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Sign Up"
                android:gravity="center" // Make the text center aligned
                android:textColor="#ffffff"
                android:textSize="21dp"
                android:textStyle="bold" />
        </LinearLayout>
    

    This makes sure that your text would cover the entire space next to the icon and center the text within it. You dont even need a LinearLayout for that. It can be removed and it'll still work.

    0 讨论(0)
提交回复
热议问题