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

Android에서 TextView 텍스트 크기를 경계에 맞게 자동 조절하는 가장 좋은 방법

이 튜토리얼에서는 Android 앱에서 TextView의 텍스트가 지정된 영역(경계) 안에 완벽하게 들어가도록 크기를 자동으로 조절하는 방법을 단계별로 살펴봅니다. 화면 크기가 다양한 기기에서 긴 텍스트가 잘리지 않고 깔끔하게 표시되어야 할 때 이 기능이 특히 유용합니다.

1단계 — 새 프로젝트 생성 및 라이브러리 추가

Android Studio를 열고 File → New Project로 이동하여 새 프로젝트를 생성합니다. 필요한 모든 세부 정보를 입력한 후 프로젝트를 만들어 주세요.

그다음 build.gradle(Module: App) 파일에 아래 두 개의 의존성을 추가합니다.

implementation 'com.android.support:design:28.0.0'
implementation 'me.grantland:autofittextview:0.2.1'

여기서 사용할 AutofitTextView 라이브러리는 일반 TextView와 동일하게 동작하지만, 텍스트가 뷰의 경계를 벗어나지 않도록 폰트 크기를 자동으로 줄여주는 기능을 제공합니다.

2단계 — 레이아웃 XML 작성

res/layout/activity_main.xml 파일에 다음 코드를 추가합니다. 여러 개의 AutofitTextView를 배치하고 각각 다른 길이의 텍스트를 넣어 자동 크기 조절 결과를 확인할 수 있도록 구성했습니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:autofit="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <me.grantland.widget.AutofitTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="2"
        android:singleLine="true"
        android:text="Android AutoFit TextView Example"
        android:textSize="42sp"
        autofit:minTextSize="5sp" />

    <me.grantland.widget.AutofitTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="2"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:singleLine="true"
        android:text="A TextView that automatically reSizes text to fit perfectly within the bounds"
        android:textSize="42sp"
        autofit:minTextSize="5sp" />

    <me.grantland.widget.AutofitTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="2"
        android:singleLine="true"
        android:text="Android AutoFit TextView"
        android:textSize="42sp"
        autofit:minTextSize="5sp" />

    <me.grantland.widget.AutofitTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="2"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:singleLine="true"
        android:text="Automatically Resized text"
        android:textSize="42sp"
        autofit:minTextSize="5sp" />

    <me.grantland.widget.AutofitTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="2"
        android:singleLine="true"
        android:text="Automatically Resize Text to Fit Perfectly within its Bounds"
        android:textSize="42sp"
        autofit:minTextSize="5sp" />

</LinearLayout>

주요 속성 설명

android:textSize="42sp"는 텍스트의 시작(최대) 크기를 지정하고, autofit:minTextSize="5sp"는 축소될 수 있는 최소 크기를 설정합니다. 텍스트가 길수록 이 범위 안에서 자동으로 크기가 조절됩니다.

3단계 — MainActivity 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다. 별도의 처리 없이 레이아웃만 연결하면 됩니다.

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

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 텍스트 크기를 경계에 맞게 자동 조절하는 가장 좋은 방법

실행 결과를 보면 텍스트 길이가 서로 다른 여러 TextView가 각자의 경계 안에 맞춰 폰트 크기가 자동으로 조절되어 표시되는 것을 확인할 수 있습니다. 짧은 문장은 원래 크기(42sp) 그대로 보이고, 긴 문장은 최소 크기(5sp)까지 줄어들면서 한 줄 안에 들어갑니다.

참고: API 26 이상에서 제공되는 기본 자동 크기 조절 기능

참고로 Android 8.0(API 26)부터는 외부 라이브러리 없이도 TextView 자체적으로 자동 크기 조절 기능을 지원합니다. minSdkVersion이 26 이상이라면 아래처럼 간단히 적용할 수 있습니다.

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:autoSizeTextType="uniform"
    android:autoSizeMinTextSize="12sp"
    android:autoSizeMaxTextSize="42sp"
    android:autoSizeStepGranularity="2sp"
    android:text="Auto Sizing Text" />

AppCompat 라이브러리를 사용하면 하위 버전에서도 app:autoSizeTextType 속성으로 동일한 기능을 활용할 수 있으니, 프로젝트 환경에 맞는 방식을 선택하시기 바랍니다.