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

Kotlin으로 안드로이드 TextView에 여러 스타일 한 번에 적용하는 방법

이 예제에서는 Kotlin을 사용해 안드로이드의 단일 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:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="150dp"
        android:padding="4dp"
        android:textAlignment="center"
        android:textSize="16sp" />
    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_marginTop="70dp"
        android:padding="4dp"
        android:textAlignment="center"
        android:textSize="16sp" />
    <TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="70dp"
        android:padding="4dp"
        android:textAlignment="center"
        android:textSize="16sp" />
</RelativeLayout>

3단계 - src/MainActivity.kt 파일에 아래 코드를 추가합니다. HTML 태그(<b>, <i>, <small>, <font>)를 문자열에 포함한 뒤 Html.fromHtml()로 변환하면 하나의 TextView 안에서도 서로 다른 스타일을 섞어 표시할 수 있습니다.

import android.os.Bundle
import android.text.Html
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
    private lateinit var textView: TextView
    private lateinit var textView2: TextView
    lateinit var textView3: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        textView = findViewById(R.id.textView)
        textView2 = findViewById(R.id.textView2)
        textView3 = findViewById(R.id.textView3)
        textView.text = Html.fromHtml(
            "Multiple style inside android textView: bold text: "
                + "<b>bold text</b>, italic text: <i>italic text</i>, small font: <small>small "
                + "text</small>, "
                + "font color: <font color=\"blue\">Text Color</font>, "
                + "font color with bold text: <font color=\"green\"><b>Bold with font "
                + "color</b></font>"
        )
        val text = Html.fromHtml(
            "Multiple style inside android textView: bold text: "
                + "<b>bold text</b>, "
                + "italic text: <i>italic text</i>, small font: <small>small text</small>, font "
                + "color: <font color=\"blue\">Text Color</font>, "
                + "font color with bold text: <font color=\"green\"><b>Bold with font "
                + "color</b></font>"
        )
        textView2.text = text
        textView3 = findViewById(R.id.textView3)
        textView3.text = Html.fromHtml(getString(R.string.textStyle))
    }
}

4단계 - res/values/strings.xml 파일을 열고 아래 코드를 추가합니다. CDATA 블록을 사용하면 XML 파서가 HTML 태그를 오류로 처리하지 않고 그대로 문자열로 전달할 수 있습니다.

<resources>
    <string name="textStyle">
    <![CDATA[
        Multiple style inside android textView: bold text: <b>bold
        text</b>, italic text: <i>italic text</i>, small font:
        <small>small text</small>,
        font color: <font color="blue">Text Color</font>, font
        color with bold text: <font color="green"><b>Bold with font
        color</b></font>
    ]]>
    </string>
</resources>

5단계 - 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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘 Kotlin으로 안드로이드 TextView에 여러 스타일 한 번에 적용하는 방법 을 클릭하고, 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기 화면에 아래와 같이 여러 스타일이 적용된 TextView가 표시됩니다.

Kotlin으로 안드로이드 TextView에 여러 스타일 한 번에 적용하는 방법

추가 팁

인자가 하나뿐인 Html.fromHtml(String)은 API 24부터 지원 중단(deprecated)되었으므로, 최신 환경에서는 Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY) 형태로 호출하는 것이 좋습니다. 또한 글자별 색상, 배경, 클릭 이벤트 등 더 세밀한 제어가 필요하다면 SpannableString이나 SpannableStringBuilder를 활용하는 방법도 함께 고려해 보세요.