[안드로이드] Toolbar(툴바) 타이틀(title) 중앙 정렬(center align)

프로그래밍/Android 관련2018. 1. 27. 20:10

안녕하세요. 개발자 드리머즈입니다.


안드로이드 툴바에서 타이틀을 중앙정렬 하는 법에 대해 배워보겠습니다. 그 전에 안드로이드 툴바가 무엇인지 간단히 보겠습니다.


위의 사진에서 빨간색으로 표시한 부분이 툴바(Toolbar)입니다. 툴바를 사용함으로써 타이틀이나 (위 사진에는 없지만 툴바 왼쪽에 위치하는) 뒤로가기 버튼 등을 쉽게 사용할 수 있습니다. 물론 툴바가 필요없는 경우에는 사용을 하지 않을 수 있으며 실제로 툴바가 없는 액티비티(Activity)도 많이 있습니다.

지금하고자 하는 것은 타이틀을 정확하게 중앙 정렬시키는 것입니다. 스택오버플로우에도 많은 답변이 달려 있습니다.


https://stackoverflow.com/questions/26533510/android-toolbar-center-title-and-custom-font


가장 많은 추천 표를 얻은 답변과 같은 방식으로 코드를 작성해봤습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@color/gonggaPink"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    >
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toolbar Title"
        android:layout_gravity="center"
        android:id="@+id/toolbar_title"
        android:textSize="20sp"
        />
 
</android.support.v7.widget.Toolbar>
cs


위의 코드처럼 <TextView>의 layout_width에 "wrap_content"값을 주고 layout_gravity="center"값을 주는게 핵심입니다. 이렇게 하면 뒤로가기 버튼이 있든지 없든지 정확하게 중앙정렬이 됩니다.



그리고 커스텀 타이틀을 사용하기 때문에 아래와 같이 기본 타이틀은 사용하지 않아야 합니다.

1
        getSupportActionBar().setDisplayShowTitleEnabled(false); //기본 타이틀 보여줄지 말지 설정
cs




*참고로 아래는 잘못된 코드입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@color/gonggaPink"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    >
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Toolbar Title"
        android:gravity="center_horizontal"
        android:id="@+id/toolbar_title"
        />
 
</android.support.v7.widget.Toolbar>
cs



위의 코드처럼 xml상에서 Toolbar에 <TextView>를 추가하고 layout_width를 "match_parent"로 gravity="center_horizontal"로 하게되면 문제가 생깁니다.

뒤로가기 버튼이 없으면 제대로 동작합니다.

 

하지만 뒤로가기 버튼을 사용한다면


위의 사진처럼 정확한 중앙정렬이 아니라 중앙에서 조금 벗어나게 자리를 잡게 됩니다.

그 이유는 TextView 내부의 글자를 중앙정렬 하도록 했는데 뒤로가기 버튼이 생기면 TextView의 영역이 줄어들기 때문입니다. 


  


  


저 처럼 실수하지 마시길 바랍니다.




작성자

Posted by 드리머즈

관련 글

댓글 영역