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

Kotlin으로 Android TextView에 줄 바꿈 추가하는 방법 완벽 가이드

이 튜토리얼에서는 Kotlin을 사용하여 Android 앱의 TextView에 줄 바꿈(line break)을 추가하는 방법을 단계별로 알아봅니다. strings.xml 리소스 파일에서 <br> 태그와 \n 문자를 활용하면 하나의 TextView 안에서 여러 줄의 텍스트를 깔끔하게 표시할 수 있습니다.

1단계: 새 프로젝트 생성

Android Studio를 실행하고 File ⇒ New Project 메뉴로 이동한 뒤, 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.

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

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Tutorials Point"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="32sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/Questions"
        android:textSize="24sp" />
</RelativeLayout>

3단계: MainActivity.kt 작성

src/MainActivity.kt 파일에 다음 코드를 추가합니다. findViewById로 TextView를 가져온 후 setTextColor() 메서드로 텍스트 색상을 변경합니다.

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        val textView: TextView = findViewById(R.id.textView)
        textView.setTextColor(Color.RED);
    }
}

4단계: strings.xml에서 줄 바꿈 처리

핵심 부분입니다. res/strings.xml 파일을 열고 아래와 같이 작성합니다. 각 질문 항목을 <br></br> 태그로 감싸고 문장 끝에 \n(줄 바꿈 문자)을 넣어 TextView에서 줄이 바뀌도록 처리합니다.

<resources>
    <string name="app_name">Q5</string>
    <string name="Questions">
        <br>
            1. What is your Favourite food? \n
        </br>
        <br>
            2. Which is your favourite sport?\n
        </br>
        <br>
            3. Whats your bucket list?
        </br>
    </string>
</resources>

5단계: AndroidManifest.xml 설정

androidManifest.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">
    <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 ▶ 아이콘을 클릭합니다. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 연결된 기기 화면에 아래와 같이 줄 바꿈이 적용된 결과가 표시됩니다.

Kotlin으로 Android TextView에 줄 바꿈 추가하는 방법 완벽 가이드

마무리 정리

Android TextView에서 줄 바꿈을 구현하는 핵심 포인트는 다음과 같습니다.

• strings.xml에서 각 문장을 <br> 태그로 감싸거나 문장 끝에 \n을 추가합니다.
• Kotlin 코드에서는 findViewById()로 TextView 인스턴스를 가져와 속성을 동적으로 변경할 수 있습니다.
• 실행 버튼을 눌러 실제 기기나 에뮬레이터에서 결과를 확인합니다.