개요
이 튜토리얼에서는 안드로이드 앱 개발 시 색상 정수(Integer) 값을 16진수(HEX) 색상 문자열로 변환하는 방법을 단계별 예제와 함께 살펴봅니다. 자바의 Integer.toHexString() 메서드를 활용하면 간단하게 변환할 수 있습니다.
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:textSize="24sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>3단계 — MainActivity 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다.
import androidx.appcompat.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 textView = findViewById(R.id.textView);
int intColor = -16895234;
String hexColor = Integer.toHexString(intColor).substring(2);
textView.setText("#"+hexColor);
}
}코드 설명: Integer.toHexString()는 정수를 16진수 문자열로 반환합니다. 음수인 색상 값은 알파 채널을 포함한 8자리 HEX 값(예: fefe32fe)으로 출력되므로, substring(2)를 사용해 앞의 두 글자(알파 값)를 제거하고 RGB 6자리 HEX 코드만 추출합니다. 최종적으로 화면에는 #fe32fe 형태로 표시됩니다.
4단계 — 매니페스트 파일 확인
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 아이콘을 클릭하세요. 실행 옵션에서 모바일 기기를 선택하면, 연결된 기기 화면에 변환된 HEX 색상 코드가 표시됩니다.
