이 튜토리얼에서는 안드로이드(Android)에서 TextView의 글꼴(텍스트) 색상을 변경하는 방법을 단계별로 살펴봅니다. 텍스트 색상은 XML 속성 또는 Java 코드로 지정할 수 있는데, 이번 예제에서는 setTextColor() 메서드를 사용해 코드에서 동적으로 색상을 적용하는 방법을 다룹니다.
1단계 — Android Studio에서 새 프로젝트 만들기
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/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="My color is Blue" android:layout_centerInParent="true" android:textStyle="bold" android:textSize="36sp"/> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textView1" android:layout_marginBottom="10dp" android:text="My color is Green" android:textStyle="bold" android:layout_centerInParent="true" android:textSize="36sp" /> </RelativeLayout>
3단계 — MainActivity.java 코드 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다. setTextColor() 메서드를 호출해 각 TextView의 글자 색상을 변경합니다.
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView1 = findViewById(R.id.textView1);
textView1.setTextColor(Color.BLUE);
TextView textView2 = findViewById(R.id.textView2);
textView2.setTextColor(Color.parseColor("#006400"));
}
}
색상 지정 방식 정리
- 기본 색상 상수 사용:
Color.BLUE처럼Color클래스가 제공하는 미리 정의된 색상 상수를 그대로 전달합니다. - HEX 색상 코드 사용:
Color.parseColor("#006400")처럼 16진수 색상 코드를 문자열로 넘기면 원하는 색을 더욱 정밀하게 지정할 수 있습니다.
참고로 XML에서 바로 색상을 지정하고 싶다면 android:textColor="#006400" 속성을 사용하는 방법도 있습니다.
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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 실행 옵션에서 본인의 모바일 기기를 선택하면, 기기 화면에 앱이 실행되며 파란색과 진한 초록색(#006400)으로 표시된 텍스트를 확인할 수 있습니다.
