이 튜토리얼에서는 안드로이드 앱이 실행되는 도중(런타임)에 TextView의 스타일을 동적으로 변경하는 방법을 단계별로 알아봅니다. 화면의 텍스트를 탭하면 글자 스타일과 배경색이 전환되는 간단한 예제를 직접 만들어 보겠습니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File → New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 정보를 모두 입력하여 프로젝트를 만듭니다.
2단계 — 레이아웃 파일 작성 (activity_main.xml)
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 정중앙에 TextView 하나를 배치하는 구성입니다.
<?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="wrap_content" android:layout_height="wrap_content" android:text="Have a nice day!" android:textSize="36sp" android:layout_centerInParent="true"/> </RelativeLayout>
3단계 — 스타일 정의 (styles.xml)
res/values/styles.xml에 두 가지 스타일을 정의합니다. boldText는 굵은 기울임체에 흰색 글자를 적용하고, normalText는 기본 스타일에 은회색 글자를 적용합니다.
<resources> <style name="boldText"> <item name="android:textStyle">bold|italic</item> <item name="android:textColor">#FFFFFF</item> </style> <style name="normalText"> <item name="android:textStyle">normal</item> <item name="android:textColor">#C0C0C0</item> </style> </resources>
4단계 — 색상 리소스 추가
강조 상태와 일반 상태에서 사용할 배경색 리소스를 정의합니다. 아래 예제에서는 strings.xml에 함께 넣었지만, 실제 프로젝트에서는 res/values/colors.xml 파일로 분리해 관리하는 것이 좋습니다.
<resources> <string name="app_name">Sample</string> <color name="highlightedTextViewColor">#000088</color> <color name="normalTextViewColor">#000044</color> </resources>
5단계 — 메인 액티비티 작성 (MainActivity.java)
src/MainActivity.java에 아래 코드를 추가합니다. TextView를 클릭하면 기기의 API 레벨(API 23 마시멜로)에 따라 적절한 setTextAppearance() 메서드를 호출해 boldText 스타일을 적용하고, 배경색도 강조 색상으로 함께 변경합니다.
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT < 23) {
textView.setTextAppearance(getApplicationContext(), R.style.boldText);
} else {
textView.setTextAppearance(R.style.boldText);
}
textView.setBackgroundResource(R.color.highlightedTextViewColor);
}
});
}
}
참고: setTextAppearance()는 현재 deprecated된 API입니다. 최신 프로젝트(AndroidX 환경)에서는 TextViewCompat.setTextAppearance(textView, R.style.boldText)를 사용하는 것이 권장됩니다. 또한 Android Studio의 최신 버전에서는 스타일 파일 이름이 themes.xml로 표시될 수 있습니다.
6단계 — 매니페스트 설정 (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 Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 버튼을 클릭한 뒤, 목록에서 자신의 모바일 기기를 선택하면 됩니다. 앱이 실행되면 처음에는 기본 스타일의 텍스트가 표시됩니다.

화면의 텍스트를 탭하면 boldText 스타일이 적용되어 글자가 굵은 기울임체 흰색으로 바뀌고, 배경색도 진한 파란색으로 전환됩니다.
