Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android TextView에서 텍스트를 가로·세로 가운데 정렬하는 방법

이 튜토리얼에서는 Android의 TextView에서 텍스트를 가로 및 세로 방향으로 가운데 정렬하는 방법을 단계별로 살펴봅니다. 핵심은 android:gravity 속성을 활용하는 것입니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project를 선택해 새 프로젝트를 만들고, 필요한 모든 정보를 입력하여 프로젝트 설정을 완료합니다.

2단계 — 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 두 개의 TextView를 배치하고, 하나에는 세로 중앙 정렬(center_vertical), 다른 하나에는 가로 중앙 정렬(center_horizontal)을 적용했습니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:text="Text in Center Vertical" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:text="Text in Center Horizontal" />
</RelativeLayout>

gravity 속성 주요 값 정리

  • center_vertical: 세로 방향으로만 중앙 정렬
  • center_horizontal: 가로 방향으로만 중앙 정렬
  • center: 가로와 세로 모두 한 번에 중앙 정렬

가로와 세로 정렬을 동시에 적용하려면 android:gravity="center"처럼 값을 하나로 지정하면 됩니다. 참고로 android:gravity는 뷰 내부 콘텐츠의 정렬을 결정하고, android:layout_gravity는 부모 레이아웃 안에서 뷰 자체의 위치를 결정한다는 점도 함께 기억해 두면 좋습니다.

3단계 — MainActivity.java 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다.

package app.com.sample;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

4단계 — AndroidManifest.xml 확인

androidManifest.xml 파일이 아래 코드와 같이 구성되어 있는지 확인합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행하기

이제 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 Android 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 기기 목록에서 사용 중인 모바일 기기를 선택하면, 해당 기기 화면에 텍스트가 가운데 정렬된 기본 화면이 표시됩니다.

Android TextView에서 텍스트를 가로·세로 가운데 정렬하는 방법